中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

spring boot整合scurity如何實現簡單的登錄校驗

發布時間:2020-08-04 14:09:06 來源:億速云 閱讀:170 作者:小豬 欄目:編程語言

這篇文章主要講解了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<&#63; 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如何實現簡單的登錄校驗有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

托里县| 普陀区| 遵化市| 桃园县| 平江县| 双流县| 甘德县| 云南省| 丹巴县| 监利县| 团风县| 鄂尔多斯市| 冀州市| 东乌| 南溪县| 涪陵区| 齐齐哈尔市| 故城县| 渝中区| 建始县| 乌恰县| 偏关县| 揭西县| 奇台县| 苏尼特右旗| 静宁县| 文安县| 西丰县| 桐柏县| 焦作市| 峨眉山市| 融水| 石林| 图木舒克市| 邵东县| 监利县| 洪湖市| 确山县| 蓝田县| 崇州市| 沂水县|