spring boot Security 簡單使用
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供金州網(wǎng)站建設(shè)、金州做網(wǎng)站、金州網(wǎng)站設(shè)計、金州網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、金州企業(yè)網(wǎng)站模板建站服務(wù),十余年金州做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
引入依賴
<!-- 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() // 定義當(dāng)需要用戶登錄時候,轉(zhuǎn)到的登錄頁面。
// .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<>();//權(quán)限集合
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 類還有很可以使用的函數(shù)
請參考:
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://bm7419.com/article32/jcespc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、App開發(fā)、品牌網(wǎng)站設(shè)計、網(wǎng)站營銷、虛擬主機、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)