新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
springbootSecurity簡(jiǎn)單使用
spring boot Security 簡(jiǎn)單使用
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供金州網(wǎng)站建設(shè)、金州做網(wǎng)站、金州網(wǎng)站設(shè)計(jì)、金州網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、金州企業(yè)網(wǎng)站模板建站服務(wù),十余年金州做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
引入依賴
org.springframework.boot spring-boot-starter-security 配置 SecurityConfig@Configuration
br/>@Configuration@Autowired UserDetailServiceImpl userDetailService; @Autowired LoginSuccessHandler loginSuccessHandler; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //自定義用戶驗(yàn)證和加密方式 auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 定義當(dāng)需要用戶登錄時(shí)候,轉(zhuǎn)到的登錄頁(yè)面。 // .loginPage("/login.html") //自定義登錄頁(yè)面 // .loginProcessingUrl("/login") //自定義登錄接口地址 .successHandler(loginSuccessHandler) .and() // 定義哪些URL需要被保護(hù)、哪些不需要被保護(hù) .authorizeRequests().antMatchers("/login").permitAll() //不需要保護(hù)的URL .anyRequest() // 任何請(qǐng)求,登錄后可以訪問(wèn) .authenticated() .and() .logout().logoutSuccessUrl("/login").permitAll() // 登出 .and() .csrf().disable(); } }
3.用戶驗(yàn)證處理
@Component
public class UserDetailServiceImpl implements UserDetailsService {
/**
* 用戶校驗(yàn)
* @param s
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Collection 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ù)
請(qǐng)參考:
https://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html
----end----
當(dāng)前標(biāo)題:springbootSecurity簡(jiǎn)單使用
轉(zhuǎn)載來(lái)源:http://fisionsoft.com.cn/article/jcespc.html