为什么Spring Security hasRole函数不能对任何api进行身份验证

我很难在spring security hasRole下使用它。我在数据库中有2个角色,分别保存为 ROLE_ADMIN ROLE_USER 。我想给permisson一些具有ADMIN角色的API,一些具有USER角色的API。这是我的代码。

SecurityConfig

@Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private DataSource dataSource;

        @Value("${spring.queries.users-query}")
        private String usersQuery;

        @Value("${spring.queries.roles-query}")
        private String rolesQuery;

        @Override
        public void configure(AuthenticationmanagerBuilder auth) throws Exception {

            auth
                    .jdbcAuthentication()
                    .dataSource(dataSource)
                    .passwordEncoder(bCryptPasswordEncoder())
                    .usersByusernameQuery(usersQuery)
                    .authoritiesByusernameQuery(rolesQuery);
        }

        @Override
        protected void configure(HttpSecurity http) {
            System.out.println("configure " );
            try {
                http.csrf().disable().authorizeRequests()
                        .antMatchers("/","/*.html").permitAll()
                        .antMatchers("/home").permitAll()
                        .antMatchers("/login").permitAll()
                        .antMatchers("/profile/").hasAnyRole("ADMIN","USER")

                        .antMatchers("/admin/*").hasRole("ADMIN")
                        .antMatchers("/insurance/*").hasRole("ADMIN")
                        .antMatchers("/company/*").hasRole("ADMIN")
                        .anyRequest().authenticated();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void configure(WebSecurity web) {
            web.httpFirewall(allowUrlEncodedSlashHttpFirewall())
                    .ignoring()
                    .antMatchers("/resources/**","/static/**","/css/**","/js/**","/images/**","/templates/**");

        }

        @Bean
        public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
            StrictHttpFirewall firewall = new StrictHttpFirewall();
        /*firewall.setallowUrlEncodedSlash(true);
        firewall.setallowSemicolon(true);*/
            firewall.setallowUrlEncodedDoubleSlash(true);
            return firewall;
        }

        @Bean
        public BCryptPasswordEncoder bCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }
}

我在sql queries中有application.properties

spring.queries.users-query=select username,password,status from insurance.users where username=?
spring.queries.roles-query=select u.username,r.role from insurance.users u inner join insurance.roles r on(u.role_id=r.id) where u.username=?

问题是当我尝试登录时,我得到403错误代码。

这是Controller.class

 @RequestMapping(value = "/login",method = RequestMethod.POST)
        public String login(@RequestParam(value = "email") String email,@RequestParam(value = "password") String password,HttpSession session) {
            Result result = userService.login(email,password);
            session.setattribute("user",result.getData());

            if(result.getStatus() == 200){
                return  "redirect:/profile";
            } else {
                return "redirect:/login?error";
            }
        }

        @RequestMapping(value = "/profile",method = RequestMethod.GET)
        public String profile(HttpSession httpSession,Model model) {
            if(httpSession.getattribute("user") != null) {
                UserResponse user = (UserResponse) httpSession.getattribute("user");
                model.addAttribute("user",user);
                return "profile";
            } else {
                return "redirect:/home";
            }
        }

我试图解决它,但是找不到。如果您有任何建议,请告诉。

我按照建议更改了配置文件。我添加了自定义登录逻辑,现在当我想进入/ admins或其他网址时,我重定向到登录网址,这是我的配置代码

protected void configure(HttpSecurity http) {
        try {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/home").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/insurance/*").hasRole("ADMIN")
                    .antMatchers("/company/*").hasRole("ADMIN")
                    .and()
                    .formLogin()
                    .loginPage("/login.html").permitAll().usernameParameter("username") .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/profile.html",true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
zhaozihong1 回答:为什么Spring Security hasRole函数不能对任何api进行身份验证

只需在例外情况下添加登录名即可进行身份验证。 试试看

protected void configure(HttpSecurity http) {
        try {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/login").permitAll()
                    .antMatchers("/home").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/insurance/*").hasRole("ADMIN")
                    .antMatchers("/company/*").hasRole("ADMIN")
                    .and()
                    .formLogin()
                    .loginPage("/login.html").permitAll().usernameParameter("username") .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/profile.html",true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
本文链接:https://www.f2er.com/3168496.html

大家都在问