1-項(xiàng)目創(chuàng)建
創(chuàng)建SpringBoot項(xiàng)目堪遂。
2-引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
引入依賴后币旧,項(xiàng)目的所有接口都會(huì)被保護(hù)起來吹菱。
3-編寫HelloController
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
4-訪問/hello,需要登錄后才可以訪問
默認(rèn)情況,用戶名是user蚌成,密碼在控制臺(tái)隨機(jī)生成担忧。
5-通過配置文件配置用戶名密碼(可選)
spring.security.user.name=chadj
spring.security.user.password=123456
6-通過Java配置用戶名密碼(可選)
創(chuàng)建SecurityConfig
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 下面這兩行配置表示在內(nèi)存中配置了兩個(gè)用戶
auth.inMemoryAuthentication()
.withUser("chadj").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")
.and()
.withUser("jichengda").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
7-登錄配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
VerifyCodeFilter verifyCodeFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
http
.authorizeRequests()//開啟登錄配置
.antMatchers("/hello").hasRole("admin")//表示訪問 /hello 這個(gè)接口惩猫,需要具備 admin 這個(gè)角色
.anyRequest().authenticated()//表示剩余的其他接口轧房,登錄之后就能訪問
.and()
.formLogin()
//定義登錄頁面,未登錄時(shí)厂镇,訪問一個(gè)需要登錄之后才能訪問的接口捺信,會(huì)自動(dòng)跳轉(zhuǎn)到該頁面
.loginPage("/login_p")
//登錄處理接口
.loginProcessingUrl("/doLogin")
//定義登錄時(shí)馍佑,用戶名的 key拭荤,默認(rèn)為 username
.usernameParameter("uname")
//定義登錄時(shí),用戶密碼的 key雏亚,默認(rèn)為 password
.passwordParameter("passwd")
//登錄成功的處理器
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("success");
out.flush();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("fail");
out.flush();
}
})
.permitAll()//和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("logout success");
out.flush();
}
})
.permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
8-忽略攔截
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/vercode");
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者