spring boot Security 簡單使用
成都創新互聯專業為企業提供金州網站建設、金州做網站、金州網站設計、金州網站制作等企業網站建設、網頁設計與制作、金州企業網站模板建站服務,十余年金州做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
引入依賴
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置 SecurityConfig@Configuration
br/>@Configuration
@Autowired
UserDetailServiceImpl userDetailService;
@Autowired
LoginSuccessHandler loginSuccessHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//自定義用戶驗證和加密方式
auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 定義當需要用戶登錄時候,轉到的登錄頁面。
// .loginPage("/login.html") //自定義登錄頁面
// .loginProcessingUrl("/login") //自定義登錄接口地址
.successHandler(loginSuccessHandler)
.and()
// 定義哪些URL需要被保護、哪些不需要被保護
.authorizeRequests().antMatchers("/login").permitAll() //不需要保護的URL
.anyRequest() // 任何請求,登錄后可以訪問
.authenticated()
.and()
.logout().logoutSuccessUrl("/login").permitAll() // 登出
.and()
.csrf().disable();
}
}
3.用戶驗證處理
@Component
public class UserDetailServiceImpl implements UserDetailsService {
/**
* 用戶校驗
* @param s
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Collection<GrantedAuthority> collection = new ArrayList<>();//權限集合
String password = new BCryptPasswordEncoder().encode("123456");
User user = new User(s,password,collection);
return user;
}
}
4.登錄成功后處理
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(authentication.getName());
}
}
HttpSecurity 類還有很可以使用的函數
請參考:
https://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html
----end----
本文名稱:springbootSecurity簡單使用
本文地址:http://www.yijiale78.com/article32/jcespc.html
成都網站建設公司_創新互聯,為您提供、App開發、品牌網站設計、網站營銷、虛擬主機、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯