• springboot中使用spring security,登录url就出现403错误


    参考链接:https://segmentfault.com/q/1010000012743613

    有两个controller,一个是所有用户可以访问的@RequestMapping("user"),
    还有一个是管理员可以访问的@RequestMapping("admin")。

    /user/login是UserController中的登录url。
    所有操作(除登录注销)都要登录之后才能进行。

    现在想用springboot结合spring security实现权限管理。
    系统是前后端分离的,controller中返回数据,不返回页面,WebMvcConfig也没有配置什么。

    但/user/login,post怎么也不通。报403错误。

    这是错误信息

     这是WebSecurityConfig

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Bean
        UserDetailsService customUserService() { //注册UserDetailsService 的bean
            return new CustomUserService();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/**").access("hasRole('ROLE_USER')")
                    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                    .anyRequest().authenticated().and() // access after login
    //                .rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("").and()
                    .formLogin().loginProcessingUrl("user/login").permitAll().and()
                    .logout().permitAll();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(customUserService());
        }
    }

    这是CustomUserService

    @Service
    public class CustomUserService implements UserDetailsService {
    
        @Autowired
        private UserService userService;
    
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            System.out.println("loadUser " + s);
            User user = userService.getUserByUsername(s);
            if (user == null || user.getIsDel() == 1) {
                throw new UsernameNotFoundException("user not exist");
            }
            List<GrantedAuthority> auths = new ArrayList<>();
            for (Role role : user.getRoles()) {
                auths.add(new SimpleGrantedAuthority(role.getName())); //不同用户会返回不同的role.name:ROLE_USER, ROLE_ADMIN
            }
            return new org.springframework.security.core.userdetails.User(s , user.getPwd(), auths);
        }
    }

    最后即使我在WebSecurity中什么也不配置,默认应该是不需要验证session吧。
    仍然不行。

    protected void configure(HttpSecurity http) throws Exception {
    }

    问题原因及解决方案:

    看错误提示,可能是因为你开启了CSRF保护,关闭即可,在configure(HttpSecurity http)方法中追加http.csrf().disable();

  • 相关阅读:
    微软一站式示例代码库 11月小结
    Linux服务器使用SSH的命令 [转]
    简明 Vim 练级攻略 [转]
    如何在Windows下使用LAPACK和ARPACK [转]
    使用setuptools自动安装python模块 [转]
    VS2010下GSL的配置 [转]
    poj3255 Roadblocks ***
    协方差矩阵的详细说明 [转]
    VC环境下LIB引用问题(LNK1104) [转]
    Dreamweaver CS5: "Configuration error"
  • 原文地址:https://www.cnblogs.com/it-deepinmind/p/12074325.html
Copyright © 2020-2023  润新知