Springboot 整合SpringSecurity

本文介绍了如何使用Spring Boot与Spring Security配置用户登录流程,包括UserDetailsService实现、认证处理器和自定义登录处理。着重讲解了如何设置角色权限及处理登录成功与失败情况,并演示了如何关闭CSRF验证。

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

  • 老规矩 先引入maven

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
  • 创建一个MyUserDatailService 这里提供了登录数据,每当有登录时 会调用 这个类 的loadUserByUsername 方法

@Service
public class MyUserDatailService implements UserDetailsService{

    @Autowired
    UserService service;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
     
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头,数据库中没有
        authorities.add(new SimpleGrantedAuthority("ROLE_" + "ADMIN"));
        //这里我们设置一个固定密码 权限为ADMIN
        return new User(
                username,
                passwordEncoder.encode("admin"),
                authorities
        );

    }
}
  • 创建两个处理器

public class OnSucessHandle implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication 				authentication) throws IOException, ServletException {
        response.getWriter().write("登录成功");
    }
}
public class OnFaildHandle implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.getWriter().write("登录失败");
    }
}

  • 创建配置类


@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDatailService userDatailService;

    /**
     * 指定加密方式
     */


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //如何有验证码加上这行
        http.addFilterBefore(new VerCodeFilter("/Login/Login"), UsernamePasswordAuthenticationFilter.class);

        http.formLogin().
        		 loginProcessingUrl("/Login/Login") //自定义登录接口
                .successHandler(new OnSucessHandle()) //登录成功处理器
                .failureHandler(new OnFaildHandle()). //登录失败处理器

                and() 
                .authorizeRequests()
                .antMatchers("/Login/**").permitAll() // 放行Login/ 开头的接口
                .anyRequest().authenticated() // 剩下接口全部需要先登录才能请求
                .and()
                .csrf().disable();// post请求要关闭csrf验证,不然访问报错;实际开发中开启,需要前端配合传递其他参数
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.
                 userDetailsService(userDatailService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

  • 如果你的登录有验证码 记着加上过滤器


public class VerCodeFilter  extends AbstractAuthenticationProcessingFilter {

    private final String LoginURL="/Login/Login";

    public VerCodeFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse)response;
        if(LoginURL.equals(req.getServletPath()) && "POST".equalsIgnoreCase(req.getMethod())){
            HttpSession session = req.getSession();

            if (session.getAttribute("code")==null ||!session.getAttribute("code").equals(req.getParameter("Code"))){
                res.getWriter().write("验证码错误");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        return null;
    }
}
  • 权限认证

	@PreAuthorize("hasAnyRole('ADMIN')")
    @GetMapping("/queryUserPage")
   	public String getTest(){
        return "asdasd";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值