使用Spring Security实现登录认证

(1)引入Spring Security 依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
 </dependency>

(2)编写Spring Security 配置类

package com.zhang.travel.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @program: travel
 * @description:
 * @author: 
 * @create: 
 **/
//Security配置类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //Spring Security配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义表单登录
        http.formLogin()
                .loginPage("/backstage/admin_login")//自定义登录页面
                .usernameParameter("username")//用户名项
                .passwordParameter("password")//密码项
                .loginProcessingUrl("/backstage/admin/login") //登录提交路径,提交后执行认证逻辑
                .successForwardUrl("/backstage/index") //登录成功后跳转路径
                .failureForwardUrl("/backstage/admin_fail"); //登录失败后跳转路径

        //权限拦截配置
        http.authorizeRequests()
                .antMatchers("/backstage/admin/login").permitAll() //登录不需要验证
                .antMatchers("/backstage/admin_fail").permitAll() //登录失败不需要验证
                .antMatchers("/backstage/admin_login").permitAll() //登录页不需要验证
                .antMatchers("/**/*.css", "/**/*.js").permitAll() //放行静态资源
                .antMatchers("/backstage/**").authenticated() //其余都要验证
                .antMatchers("/frontdesk/**").permitAll();

        //退出登录配置
        http.logout()
                .logoutUrl("/backstage/admin/logout")
                .logoutSuccessUrl("/backstage/admin_login")
                .clearAuthentication(true)
                .invalidateHttpSession(true);

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(new MyAccessDeniedHandler());//权限不足异常处理

        //关闭csrf防护
        http.csrf().disable();

        //开启跨域访问
        http.cors();

        super.configure(http);
    }
    //密码编码器
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

(3)自定义认证逻辑

@Service
public class MyUserDetailService implements UserDetailsService {
  @Autowired
  private AdminService adminService;


  // 自定义认证逻辑
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 1.认证
    Admin admin = adminService.findByAdminName(username);
    if (admin == null) {
      throw new UsernameNotFoundException("用户不存在");
     }
    if (!admin.isStatus()){
      throw new UsernameNotFoundException("用户不可用");
     }


    // 2.授权
    List<Permission> permissions = adminService.findAllPermission(username);
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    for (Permission permission : permissions) {
      grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
     }


    // 3.封装为UserDetails对象
    UserDetails userDetails = User.withUsername(admin.getUsername())
         .password(admin.getPassword())
         .authorities(grantedAuthorities)
         .build();


    // 4.返回封装好的UserDetails对象
    return userDetails;
   }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

取酒鱼食--【余九】

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

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

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

打赏作者

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

抵扣说明:

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

余额充值