您好,登錄后才能下訂單哦!
這篇文章主要講解了spring boot整合scurity如何實現簡單的登錄校驗,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
開發環境:springboot
maven引入:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth3</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如何實現簡單的登錄校驗有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。