spring security简单登录的认证

一.思路

1.先导入相关配置(使用spring security校验之后,登录拦截的配置)

2.创建一个 WebSecurityConfig 继承 WebSecurityConfigurerAdapter ,重写 configure(HttpSecurity http) 配置表单登录和登出路径和跳转页面操作和 configure(AuthenticationManagerBuilder auth)进行配置用户校验

3.创建一个 UserSecurityService 类 实现 UserDetailsService 接口,重写UserDetails loadUserByUsername(String username)进行表单登录和获取权限操作

4.创建一个 UserSecurity 类实现 UserDetails 接口,重写一些需要的字段

二。代码

1. html页面

<form action="console/login.action" method="post" class="layui-form">
<input name="loginName" placeholder="账号" type="text" lay-verify="required" maxlength="15" class="layui-input">
<hr class="hr15">
<input name="loginPassword" lay-verify="required" maxlength="20" placeholder="密码" type="password"
class="layui-input">
<hr class="hr15">
<input name="loginCaptcha" lay-verify="required" maxlength="4" placeholder="验证码" type="text"
class="layui-input">
<img onclick="this.src='console/login/captcha.json" class="login_captcha" src="console/login/captcha.json">
<hr class="hr15">
<input value="登录" lay-submit lay-filter="login" style="width:100%" type="submit">
<hr class="hr20">
</form>

(添加这一段,使页面提示登录报错信息)
<script th:inline="javascript" th:if="${param.error}">
    $(function () {
var tempErrorMsg = [[${SPRING_SECURITY_LAST_EXCEPTION!=null?SPRING_SECURITY_LAST_EXCEPTION.message:''}]];
layer.msg(tempErrorMsg);
});
</script>

2.WebSecurityConfig类

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

//@Autowired:自动注入bean,@Qualifier(""):限定哪个bean应该被自动注入
@Autowired
@Qualifier("UserSecurityService")
   private UserDetailsService userDetailsService;
    @Value("${app.basePath:}")
private String appBasePath;

@Value("${server.port:}")
private String serverPort;

@Override
protected void configure(HttpSecurity http) throws Exception {

String basePath = StringUtils.trimToEmpty(appBasePath);

http.authorizeRequests()
.anyRequest()
.permitAll();

http.formLogin()
.loginPage(basePath + ":" + serverPort + "/console/login.html")
.usernameParameter("loginName")
.passwordParameter("loginPassword")
.loginProcessingUrl("/console/login.action")
.defaultSuccessUrl(basePath + ":" + serverPort + "/console/index.html", true)
.failureForwardUrl("/console/login.html?error=true")
.permitAll();

http.logout()
.logoutUrl("/console/logout.action")
.logoutSuccessUrl(basePath + ":" + serverPort + "/console/login.html")
.permitAll();

//关闭CSRF跨域
http.csrf()
.disable();

http.headers()
.frameOptions()
.disable();
}

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

3.SecurityUserinfoService
@Component("UserSecurityService")
public class UserSecurityService implements UserDetailsService {
    @Autowired
private AdminService adminService;

public static final String CAPTCHA_PARAMETER_NAME = "loginCaptcha";

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

HttpServletRequest currentServletRequest = RequestTool.getCurrentServletRequest();
boolean b = CaptchaTool.checkCaptcha(currentServletRequest, CAPTCHA_PARAMETER_NAME);
if (b == false) {
throw new SecurityCaptchaException("图形验证码错误");
}

UserSecurity userinfo = null;
Admin admin = this.adminService.getByUserName(username);
if (admin != null) {
userinfo = new SecurityUserinfo();
userinfo.setUsername(admin.getAccount());
userinfo.setPassword(admin.getPassword());
userinfo.setEnabled(admin.getIsEnabled());
userinfo.setUserId(admin.getId());
userinfo.setAuthorities(****);//自定义设置权限
} else {
throw new UsernameNotFoundException("用户不存在");
}
return userinfo;
}
}

4.UserSecurity 
@Setter
public class UserSecurity implements UserDetails {
    private String username;
   private String password;
   private boolean accountNonExpired = true;
private boolean accountNonLocked = true;
private boolean credentialsNonExpired = true;
private boolean enabled;
  private Set<***> authorities;//权限字段,需要自己去定义
  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
   return this.authorities;
  }
  @Getter
  private String userId;
  
  @Override
  public String getPassword() {
     return this.password;
  }

  @Override
  public String getUsername() {
  return this.username;
  }

  @Override
  public boolean isAccountNonExpired() {
 return this.accountNonExpired;
  }

  @Override
  public boolean isAccountNonLocked() {
   return this.accountNonLocked;
  }

  @Override
  public boolean isCredentialsNonExpired() {
   return this.credentialsNonExpired;
  }

  @Override
  public boolean isEnabled() {  
  return this.enabled;
  }
}
注意:如果登录失败的话会出现 Bad credentials 的提示,还要添加 messages.properties 放到 resources 目录下
AbstractUserDetailsAuthenticationProvider.badCredentials=用户名或密码错误
AbstractUserDetailsAuthenticationProvider.credentialsExpired=用户凭证已过期
AbstractUserDetailsAuthenticationProvider.disabled=用户已失效
AbstractUserDetailsAuthenticationProvider.expired=用户帐号已过期
AbstractUserDetailsAuthenticationProvider.locked=用户帐号已被锁定


参考文档:
https://blog.csdn.net/java_zhaoyu/article/details/83029672
https://www.cnblogs.com/ryelqy/p/10304619.html
https://www.codeleading.com/article/5677789104/


posted @ 2020-06-09 15:04  伏沙金  阅读(334)  评论(0编辑  收藏  举报