首页 > 编程语言 > spring boot整合scurity做简单的登录校验的实现
2020
09-27

spring boot整合scurity做简单的登录校验的实现

开发环境:springboot

maven引入:

 <dependency>
  <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.2.1.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
    <version>1.0.10.RELEASE</version>
  </dependency>

1、先在数据库创建用户表,用户名为username,密码名为password。下面是我用户表的实体

 private Integer id;
/**
* 昵称
*/
private String name;
/**
* 职位
*/
private String code;
/**
* 密码
*/
private String passwd;
/**
* 用户名
*/
private String username;
/**
* 手机号
*/
private String phone;
/**
* 创建时间
*/
private Date createdTime;

2、看项目是JPA、还是mybatis。我这边项目使用的是mybatis。需要有一个方法通过用户名获取用户信息。

3、创建一个用户验证类实现 UserDetails 继承用户实体

public class SecurityUser extends SysUser implements UserDetails {
private static final long serialVersiongUID = 1l;

public SecurityUser(SysUser sysUser) {
  if (null != sysUser) {
    this.setCode(sysUser.getCode());
    this.setCreatedTime(sysUser.getCreatedTime());
    this.setId(sysUser.getId());
    this.setName(sysUser.getName());
    this.setPasswd(sysUser.getPasswd());
    this.setPhone(sysUser.getPhone());
    this.setUsername(sysUser.getUsername());
  }
}


@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
  Collection<GrantedAuthority> authorities = new ArrayList<>();
  String username = this.getUsername();
  if (username != null) {
    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(username);
    authorities.add(authority);
  }
  return authorities;
}

@Override
public String getPassword() {
  return super.getPasswd();
}

//账户是否未过期,过期无法验证
@Override
public boolean isAccountNonExpired() {
  return true;
}

//指定用户是否解锁,锁定的用户无法进行身份验证
@Override
public boolean isAccountNonLocked() {
  return true;
}

//指示是否已过期的用户的凭据(密码),过期的凭据防止认证
@Override
public boolean isCredentialsNonExpired() {
  return true;
}

//是否可用 ,禁用的用户不能身份验证
@Override
public boolean isEnabled() {
  return true;
}
}

4、重点!创建一个scurity config配置类

 @Configuration
 @EnableWebSecurity
 public class UiSecurityConfig extends WebSecurityConfigurerAdapter {

 private static final Logger logger = LoggerFactory.getLogger(UiSecurityConfig.class);

 @Override
 protected void configure(HttpSecurity http) throws Exception { //配置策略
   http.csrf().disable();
   http.authorizeRequests().
       antMatchers("/static/**").permitAll().anyRequest().authenticated().
       and().formLogin().loginPage("/login").permitAll().successHandler(loginSuccessHandler()).
       and().logout().permitAll().invalidateHttpSession(true).
       deleteCookies("JSESSIONID").logoutSuccessHandler(logoutSuccessHandler()).
       and().sessionManagement().maximumSessions(10).expiredUrl("/login");
 }

 

 @Bean
 public BCryptPasswordEncoder passwordEncoder() { //密码加密
   return new BCryptPasswordEncoder(4);
 }

 @Bean
 public LogoutSuccessHandler logoutSuccessHandler() { //登出处理
   return new LogoutSuccessHandler() {
     @Override
     public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
       try {
         SecurityUser user = (SecurityUser) authentication.getPrincipal();
         logger.info("USER : " + user.getUsername() + " LOGOUT SUCCESS ! ");
       } catch (Exception e) {
         logger.info("LOGOUT EXCEPTION , e : " + e.getMessage());
       }
       httpServletResponse.sendRedirect("/login");
     }
   };
 }

 @Bean
 public SavedRequestAwareAuthenticationSuccessHandler loginSuccessHandler() { //登入处理
   return new SavedRequestAwareAuthenticationSuccessHandler() {
     @Override
     public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
       SysUser userDetails = (SysUser) authentication.getPrincipal();
 logger.info("USER : " + userDetails.getUsername() + " LOGIN SUCCESS ! ");

 //        登录成功后重定向路径
       response.sendRedirect("/");
     }
   };
 }
 //用户登录实现
 @Bean
 public UserDetailsService userDetailsService() {  
   return new UserDetailsService() {
     @Autowired
     private SysUserDao sysUserDao;//这里是引入数据库连接dao

     @Override
     public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
       SysUser userNmae = new SysUser();
       userNmae.setUsername(s);
      List<SysUser> listUser = sysUserDao.queryAll(userNmae);//通过用户名获取个用户信息
       SysUser user = null;
      if (listUser.size() > 0) {
        user = listUser.get(0);
      }
       if (user == null) throw new UsernameNotFoundException("Username " + s + " not found");
       return new SecurityUser(user);
     }
   };
 }
}

5、基础工作准备完成开始写controller

@Controller
public class LoginController {

 
@Resource
private SessionTool sessionTool;

//  获取登录页面
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
  return "login";
}

@RequestMapping("/")
public String login(ModelMap map){
  SysUser sysUser = sessionTool.getUser();
  map.addAttribute("sysUser", sysUser);
  return "index";
}
}

6、从session获取用户信息

@Component
public class SessionTool {
public SysUser getUser() { //为了session从获取用户信息,可以配置如下
  SysUser user = new SysUser();
  SecurityContext ctx = SecurityContextHolder.getContext();
  Authentication auth = ctx.getAuthentication();
  if (auth.getPrincipal() instanceof UserDetails) user = (SysUser) auth.getPrincipal();
  return user;
}

public HttpServletRequest getRequest() {
  return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}

7、login.html页面(登录路径为login 请求方式为post,scurity自带的登录路径)

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<form action="/login" method="post">
 用户名 : <input type="text" name="username"/>
 密码 : <input type="password" name="password"/>
 <input type="submit" value="登录">
</form>
</body>
</html>

总结一下思路:

引入依赖包-》创建用户表-》创建用户表数据库查询接口-》创建用户校验类实现UserDetails接口-》创建scurity配置类继承 WebSecurityConfigurerAdapter 方法configure为配置校验策略-》创建controller配置登录页面跳转接口-》创建登陆页面用户名必须为username 密码为password 登录路径为'/login' 请求方式为post

由于scurity配置的密码检验是加密的为了测试可以在Test模块中获取加密后的密码然后存到用户表的password字段中。

  @Test
  public void encoder() {
    String password = "123123";
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
    String enPassword = encoder.encode(password);
    System.out.println(enPassword);
  }

到此这篇关于spring boot整合scurity做简单的登录校验的实现的文章就介绍到这了,更多相关springboot scurity登录校验内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧