微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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;
   }
}


原文地址:https://www.jb51.cc/wenti/3288712.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐