spring security根据权限跳转不了指定页面This application has no explicit mapping for /error, so you are seeing th

本文介绍如何在SpringBoot项目中使用Security进行角色权限控制,通过自定义AuthenticationSuccessHandler实现不同角色登录后的页面跳转。包括配置SecurityConfig类、实现MyAuthenticationSuccessHandler类以及创建对应的controller。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上大多数的方法都不好使

今天在学习springboot+security的时候发现自己设置了3个角色,在授权成功后不能跳转页面报404错误

后来了解了一下需要配置AuthenticationSuccessHandler,重写 onAuthenticationSuccess 方法,来验证不同的角色所对应的方法

数据库权限ROLE表

首先来看SecurityConfig类


@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    @Bean
    PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/dba/**").hasRole("dba")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                //授权成功后交给自定义的处理器去处理
                .successHandler(myAuthenticationSuccessHandler())
                .permitAll().and()
                .csrf().disable();
    }

    //自定义一个授权成功的处理器
    @Bean
    AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
        return  new MyAuthenticationSuccessHandler();
    }

}

然后是自定义的MyAuthenticationSuccessHandler配置类

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
        handler(request,response,authentication);
        clearAuthenticationAttributes(request);
    }


    protected void handler(HttpServletRequest request,HttpServletResponse response,Authentication authentication) throws IOException{
        String targetUrl = determinTargetUrl(authentication);
        if(response.isCommitted()){
            logger.debug("response has already been commited .Unable to reredict to "+targetUrl);
        }
        redirectStrategy.sendRedirect(request,response,targetUrl);
    }

    protected String determinTargetUrl(final Authentication authentication) {
        //需要手动设置不同权限的角色跳转的路径是哪个
        Map<String,String> roleUrlMap = new HashMap<>();
        roleUrlMap.put("ROLE_admin","/admin/hello");
        roleUrlMap.put("ROLE_dba","/dba/hello");
        roleUrlMap.put("ROLE_user","/user/hello");

        final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for(final GrantedAuthority grantedAuthority:authorities){
            String authenriyName = grantedAuthority.getAuthority();
            //查询跳转路径里面有没有角色的信息,如果匹配上直接跳转到第一个配对的路径
            if(roleUrlMap.containsKey(authenriyName)){
                return roleUrlMap.get(authenriyName);
            }
        }

        throw new IllegalStateException();
    }


    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
}

然后是对应的controller

@RestController
public class SecurityController {


    @GetMapping("/admin/hello")
    public String adminhello(){
        return "admin hello";
    }

    @GetMapping("/dba/hello")
    public String dbahello(){
        return "dba hello";
    }
    @GetMapping("/user/hello")
    public String userhello(){
        return "user hello";
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xq30397022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值