這篇文章主要講解了spring boot整合scurity如何實現(xiàn)簡單的登錄校驗,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
成都創(chuàng)新互聯(lián)公司主打移動網(wǎng)站、成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、網(wǎng)站改版、網(wǎng)絡(luò)推廣、網(wǎng)站維護、國際域名空間、等互聯(lián)網(wǎng)信息服務(wù),為各行業(yè)提供服務(wù)。在技術(shù)實力的保障下,我們?yōu)榭蛻舫兄Z穩(wěn)定,放心的服務(wù),根據(jù)網(wǎng)站的內(nèi)容與功能再決定采用什么樣的設(shè)計。最后,要實現(xiàn)符合網(wǎng)站需求的內(nèi)容、功能與設(shè)計,我們還會規(guī)劃穩(wěn)定安全的技術(shù)方案做保障。
開發(fā)環(huán)境:springboot
maven引入:
org.springframework.security.oauth spring-security-oauth3 2.2.1.RELEASE org.springframework.security spring-security-jwt 1.0.10.RELEASE
1、先在數(shù)據(jù)庫創(chuàng)建用戶表,用戶名為username,密碼名為password。下面是我用戶表的實體
private Integer id; /** * 昵稱 */ private String name; /** * 職位 */ private String code; /** * 密碼 */ private String passwd; /** * 用戶名 */ private String username; /** * 手機號 */ private String phone; /** * 創(chuàng)建時間 */ private Date createdTime;
2、看項目是JPA、還是mybatis。我這邊項目使用的是mybatis。需要有一個方法通過用戶名獲取用戶信息。
3、創(chuàng)建一個用戶驗證類實現(xiàn) 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() { Collectionauthorities = 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; } //指示是否已過期的用戶的憑據(jù)(密碼),過期的憑據(jù)防止認證 @Override public boolean isCredentialsNonExpired() { return true; } //是否可用 ,禁用的用戶不能身份驗證 @Override public boolean isEnabled() { return true; } }
4、重點!創(chuàng)建一個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("/"); } }; } //用戶登錄實現(xiàn) @Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Autowired private SysUserDao sysUserDao;//這里是引入數(shù)據(jù)庫連接dao @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { SysUser userNmae = new SysUser(); userNmae.setUsername(s); ListlistUser = 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、基礎(chǔ)工作準備完成開始寫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自帶的登錄路徑)
Title
總結(jié)一下思路:
引入依賴包-》創(chuàng)建用戶表-》創(chuàng)建用戶表數(shù)據(jù)庫查詢接口-》創(chuàng)建用戶校驗類實現(xiàn)UserDetails接口-》創(chuàng)建scurity配置類繼承 WebSecurityConfigurerAdapter 方法configure為配置校驗策略-》創(chuàng)建controller配置登錄頁面跳轉(zhuǎn)接口-》創(chuàng)建登陸頁面用戶名必須為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); }
看完上述內(nèi)容,是不是對spring boot整合scurity如何實現(xiàn)簡單的登錄校驗有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。