01
首先要清楚,SpringSecurity只需要一些配置类,就可以实现权限控制和认证。
权限管理核心两部分:认证和授权。
Spring Security的几种登录认证方式
1.HttpBasic模式,这个模式在实际项目应用中并不适合,因为我们往往都是自己开发一个自定义的登陆页面,而FormLogin模式就支持这种需求
2.自定义表单登录,通过添加配置类继承WebSecurityConfigurerAdapter类,并重载里面的config方法实现
1. 编写login.html;
2. 创建一个继承WebSecurityConfigurerAdapter的类
3. 重写configure(HttpSecurity http)配置登录验证逻辑;
4. 重写configure(AuthenticationManagerBuilder auth)实现内存中身份认证
5. 运行验证
3.前后端分离架构的认证(同样需要继承WebSecurityConfigurerAdapter类,并重载里面的config方法,配置认证和授权)
1. 修改login.html,使用JSON传递数据;
2. 实现AuthenticationSuccessHandler接口编写自定义登录成功时的处理逻辑;
3. 实现AuthenticationFailureHandler接口自定义登录失败时的处理逻辑;
3. 运行验证。
数据库的认证和授权
实现一个自定义的UserDetailsService,
UserDetailsService仅定义了一个loadUserByUsername方法,用于获取一个UserDetails对象。
UserDetails对象包含了一系列在验证时,会用到的信息,包括用户名,密码、权限等,spring Security根据这些信息判断验证是否成功。UserDetails接口源码如下:
public interface UserDetails extends Serializable {
// ~ Methods
// ========================================================================================================
/**
* Returns the authorities granted to the user. Cannot return <code>null</code>.
*
* @return the authorities, sorted by natural key (never <code>null</code>)
*/
Collection<? extends GrantedAuthority> getAuthorities();
/**
* Returns the password used to authenticate the user.
*
* @return the password
*/
String getPassword();
/**
* Returns the username used to authenticate the user. Cannot return <code>null</code>.
*
* @return the username (never <code>null</code>)
*/
String getUsername();
/**
* Indicates whether the user's account has expired. An expired account cannot be
* authenticated.
*
* @return <code>true</code> if the user's account is valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isAccountNonExpired();
/**
* Indicates whether the user is locked or unlocked. A locked user cannot be
* authenticated.
*
* @return <code>true</code> if the user is not locked, <code>false</code> otherwise
*/
boolean isAccountNonLocked();
/**
* Indicates whether the user's credentials (password) has expired. Expired
* credentials prevent authentication.
*
* @return <code>true</code> if the user's credentials are valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isCredentialsNonExpired();
/**
* Indicates whether the user is enabled or disabled. A disabled user cannot be
* authenticated.
*
* @return <code>true</code> if the user is enabled, <code>false</code> otherwise
*/
boolean isEnabled();
}
02 Docker
03 Spring Security 结合 Jwt:
1.创建JwtUtils工具类,用来生成jwt的token和token的验证刷新之类
2.创建filter类,并配置注入security配置文件中
3.创建DAO,Service,Controller实现接口
4.创建AuthenticationFilter类,实现token校验功能