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

  • 相关阅读:
    LeetCode-Pascal's Triangle
    macOS Sierra 10.12版本 显示隐藏文件
    Android主页导航:fragment+viewpager
    (转)Android工程出现 java.lang.NoClassDefFoundError错误解决方法
    Android Studio安装以及Fetching android sdk component information超时的解决方案
    Android项目使用Ant多渠道打包(最新sdk)
    eclipse或Myeclipse中web项目没有run on server时怎么办?
    mysq查询语句包含中文以及中文乱码,字符集 GBK、GB2312、UTF8的区别
    论HTML的div、span和label的区别
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/14136963.html
Copyright © 2011-2022 走看看