spring boot整合scurity做簡(jiǎn)單的登錄校驗(yàn)的實(shí)現(xiàn)
開(kāi)發(fā)環(huán)境: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、先在數(shù)據(jù)庫(kù)創(chuàng)建用戶(hù)表,用戶(hù)名為username,密碼名為password。下面是我用戶(hù)表的實(shí)體
private Integer id; /** * 昵稱(chēng) */ private String name; /** * 職位 */ private String code; /** * 密碼 */ private String passwd; /** * 用戶(hù)名 */ private String username; /** * 手機(jī)號(hào) */ private String phone; /** * 創(chuàng)建時(shí)間 */ private Date createdTime;
2、看項(xiàng)目是JPA、還是mybatis。我這邊項(xiàng)目使用的是mybatis。需要有一個(gè)方法通過(guò)用戶(hù)名獲取用戶(hù)信息。
3、創(chuàng)建一個(gè)用戶(hù)驗(yàn)證類(lèi)實(shí)現(xiàn) UserDetails 繼承用戶(hù)實(shí)體
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();
}
//賬戶(hù)是否未過(guò)期,過(guò)期無(wú)法驗(yàn)證
@Override
public boolean isAccountNonExpired() {
return true;
}
//指定用戶(hù)是否解鎖,鎖定的用戶(hù)無(wú)法進(jìn)行身份驗(yàn)證
@Override
public boolean isAccountNonLocked() {
return true;
}
//指示是否已過(guò)期的用戶(hù)的憑據(jù)(密碼),過(guò)期的憑據(jù)防止認(rèn)證
@Override
public boolean isCredentialsNonExpired() {
return true;
}
//是否可用 ,禁用的用戶(hù)不能身份驗(yàn)證
@Override
public boolean isEnabled() {
return true;
}
}
4、重點(diǎn)!創(chuàng)建一個(gè)scurity config配置類(lèi)
@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("/");
}
};
}
//用戶(hù)登錄實(shí)現(xiàn)
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Autowired
private SysUserDao sysUserDao;//這里是引入數(shù)據(jù)庫(kù)連接dao
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
SysUser userNmae = new SysUser();
userNmae.setUsername(s);
List<SysUser> listUser = sysUserDao.queryAll(userNmae);//通過(guò)用戶(hù)名獲取個(gè)用戶(hù)信息
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、基礎(chǔ)工作準(zhǔn)備完成開(kāi)始寫(xiě)controller
@Controller
public class LoginController {
@Resource
private SessionTool sessionTool;
// 獲取登錄頁(yè)面
@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獲取用戶(hù)信息
@Component
public class SessionTool {
public SysUser getUser() { //為了session從獲取用戶(hù)信息,可以配置如下
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頁(yè)面(登錄路徑為login 請(qǐng)求方式為post,scurity自帶的登錄路徑)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> 用戶(hù)名 : <input type="text" name="username"/> 密碼 : <input type="password" name="password"/> <input type="submit" value="登錄"> </form> </body> </html>
總結(jié)一下思路:
引入依賴(lài)包-》創(chuàng)建用戶(hù)表-》創(chuàng)建用戶(hù)表數(shù)據(jù)庫(kù)查詢(xún)接口-》創(chuàng)建用戶(hù)校驗(yàn)類(lèi)實(shí)現(xiàn)UserDetails接口-》創(chuàng)建scurity配置類(lèi)繼承 WebSecurityConfigurerAdapter 方法configure為配置校驗(yàn)策略-》創(chuàng)建controller配置登錄頁(yè)面跳轉(zhuǎn)接口-》創(chuàng)建登陸頁(yè)面用戶(hù)名必須為username 密碼為password 登錄路徑為'/login' 請(qǐng)求方式為post
由于scurity配置的密碼檢驗(yàn)是加密的為了測(cè)試可以在Test模塊中獲取加密后的密碼然后存到用戶(hù)表的password字段中。
@Test
public void encoder() {
String password = "123123";
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
String enPassword = encoder.encode(password);
System.out.println(enPassword);
}
到此這篇關(guān)于spring boot整合scurity做簡(jiǎn)單的登錄校驗(yàn)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot scurity登錄校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何解決getReader() has already been called&
這篇文章主要介紹了如何解決getReader() has already been called for this request問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
詳談@Cacheable不起作用的原因:bean未序列化問(wèn)題
這篇文章主要介紹了@Cacheable不起作用的原因:bean未序列化問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
一文詳解如何配置MyBatis實(shí)現(xiàn)打印可執(zhí)行的SQL語(yǔ)句
在MyBatis中,動(dòng)態(tài)SQL是一個(gè)強(qiáng)大的特性,允許我們?cè)赬ML映射文件或注解中編寫(xiě)條件語(yǔ)句,根據(jù)運(yùn)行時(shí)的參數(shù)來(lái)決定SQL的具體執(zhí)行內(nèi)容,這篇文章主要給大家介紹了關(guān)于如何配置MyBatis實(shí)現(xiàn)打印可執(zhí)行的SQL語(yǔ)句的相關(guān)資料,需要的朋友可以參考下2024-08-08
使用RedisAtomicLong優(yōu)化性能問(wèn)題
這篇文章主要介紹了使用RedisAtomicLong優(yōu)化性能問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
IDEA?Error:java:無(wú)效的源發(fā)行版:13的解決過(guò)程
之前用idea運(yùn)行時(shí),也會(huì)出現(xiàn)這種情況,后面通過(guò)網(wǎng)上的資料解決了這個(gè)問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于IDEA?Error:java:無(wú)效的源發(fā)行版:13的解決過(guò)程,需要的朋友可以參考下2023-01-01

