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),所有系统没有用户存储支撑认证过程,所以系统相当于没有用户,所以没有人可以认证成功。

  • 相关阅读:
    Android开发历程_8(Tween Animation的2种属性设置方法)
    Kinect+OpenNI学习笔记之1(开发环境的建立)
    Android开发历程_12(Handler的使用)
    Qt学习之路_11(简易多文档编辑器)
    特征点检测学习_1(sift算法)
    Android开发历程_9(Frame Animation的使用)
    Qt学习之路_13(简易俄罗斯方块)
    总结系列_12(XML使用总结,续...)
    Android开发历程_11(AnimationListener的使用方法)
    Android开发历程_18(XML文件解析)
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/14136963.html
Copyright © 2011-2022 走看看