zoukankan      html  css  js  c++  java
  • Spring MVC Unauthorized问题

    Spring MVC Unauthorized问题

    接口源码:

    @RestController
    @RequestMapping("user/")
    @Api(tags = "用户管理")
    public class UserController {
    
        private final UserService userService;
    
        @Autowired
        public UserController(UserService userService) {
            this.userService = userService;
        }
    
        @PostMapping("login")
        @ApiOperation("用户登陆")
        public Message login(@RequestBody UserEntity loginUser) {
            return userService.login(loginUser);
        }
    }
    

    使用postman访问接口,得到的信息:

    {
        "timestamp": "2020-12-14 02:00:55",
        "status": 401,
        "error": "Unauthorized",
        "message": "Unauthorized",
        "path": "/user/test_token"
    }
    

    使用浏览器访问接口,自动跳转到的页面:

    问题排查:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    系统使用了Spring Security,而Spring Security默认对所有路径进行权限认证,并且提供默认的登陆页面。如果系统最终没有使用到Spring Security,将该依赖移除即可解决问题;如果系统确实需要使用Spring Security,那么可以自定义路径鉴权方式:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequest()              
                // 直接放行
                .antMatchers("/auth/**", "/error/**", "/dev/**").permitAll()
                // 权限认证
                .anyRequest().authenticated();
        }
    }
    

    Spring Security默认的configure(HttpSecurity httpSecurity)实际上等同于如下配置:

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequest()
                // 对所有http请求进行权限认证
                .anyRequest().authenticated().and()
                // 支持基于表单的登陆
                .formLogin().and()
                // 支持基于Basic方式的认证
                .httpBasic();
        }
    

    同时,由于没有重载configure(AuthenticationManagerBuilder),所有系统没有用户存储支撑认证过程,所以系统相当于没有用户,所以没有人可以认证成功。

  • 相关阅读:
    TSQL编程的全局变量
    一、读大学,究竟读什么?
    受用一生的心理寓言
    字符串函数
    android wait notify实现线程挂起与恢复
    Java Thread.interrupt 中断JAVA线程
    android实现文件下载功能的3种方法
    Android startActivityForResult 和 setResult的使用
    Android 软键盘盖住输入框的问题
    Android蓝牙操作
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/14136963.html
Copyright © 2011-2022 走看看