生活随笔
收集整理的這篇文章主要介紹了
SpringBoot集成Spring Security(一)登录注销
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
同個人網站 https://www.serendipper-x.cn/,歡迎訪問 !
SpringBoot集成Spring Security(二)注冊 、密碼加密、修改密碼
寫在前面
Spring Security是一種基于 Spring AOP 和 Servlet 過濾器的安全框架。它提供全面的安全性解決方案,同時在 Web 請求級和方法調用級處理身份確認和授權。
由于最近寫的項目用到了這方面知識,這里做一些總結。下面直接看代碼
一、創建項目
這里以多模塊項目為例。
多模塊項目優點: 幫助項目劃分模塊,鼓勵重用,防止POM變得過于龐大,方便各個模塊的構建,而不用每次都構建整個項目,使得針對某個模塊的特殊控制更為方便。
二、引入pom依賴
<dependency><groupId>org.springframework.security
</groupId><artifactId>spring-security-test
</artifactId><scope>test
</scope></dependency>
三、web層
項目最核心的代碼
SecurityConfig.java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate StudentService studentService
;@Autowiredprivate ObjectMapper objectMapper
;@BeanPasswordEncoder
passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(AuthenticationManagerBuilder auth
) throws Exception
{auth
.userDetailsService(studentService
).passwordEncoder(new BCryptPasswordEncoder());}@Overrideprotected void configure(HttpSecurity http
) throws Exception
{http
.httpBasic().authenticationEntryPoint((request
,response
,authException
) -> {response
.setContentType("application/json;charset=utf-8");response
.setStatus(HttpServletResponse
.SC_FORBIDDEN
);PrintWriter out
= response
.getWriter();RespBean error
= RespBean
.error("未登錄");String s
= new ObjectMapper().writeValueAsString(error
);out
.write(s
);out
.flush();out
.close();}).and().authorizeRequests().anyRequest().authenticated() .and().formLogin() .usernameParameter("username").passwordParameter("password").permitAll().failureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest req
, HttpServletResponse resp
, AuthenticationException exception
) throws IOException
, ServletException
{resp
.setContentType("application/json;charset=utf-8");resp
.setStatus(HttpServletResponse
.SC_UNAUTHORIZED
);PrintWriter out
= resp
.getWriter();RespBean respBean
= RespBean
.error("登錄失敗!");if (exception
instanceof UsernameNotFoundException || exception
instanceof BadCredentialsException) {respBean
.setMsg("用戶名或者密碼輸入錯誤,請重新輸入!");} else if (exception
instanceof DisabledException) {respBean
.setMsg("賬戶被禁用");} else {respBean
.setMsg("未知錯誤");}out
.write(objectMapper
.writeValueAsString(respBean
));out
.flush();out
.close();}}).successHandler(new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest req
, HttpServletResponse resp
, Authentication authentication
) throws IOException
, ServletException
{resp
.setContentType("application/json;charset=utf-8");PrintWriter out
= resp
.getWriter();Student student
= (Student
) authentication
.getPrincipal();student
.setPassword(null
);RespBean ok
= RespBean
.ok("登錄成功!", student
);String s
= new ObjectMapper().writeValueAsString(ok
);out
.write(s
);out
.flush();out
.close();}}).and().exceptionHandling().accessDeniedHandler((request
,response
,ex
) -> {response
.setContentType("application/json;charset=utf-8");response
.setStatus(HttpServletResponse
.SC_FORBIDDEN
);PrintWriter out
= response
.getWriter();out
.write(new ObjectMapper().writeValueAsString(RespBean
.error("權限不足")));out
.flush();out
.close();}).and().logout().logoutSuccessHandler(new LogoutSuccessHandler() {@Overridepublic void onLogoutSuccess(HttpServletRequest req
, HttpServletResponse resp
, Authentication authentication
) throws IOException
, ServletException
{resp
.setContentType("application/json;charset=utf-8");PrintWriter out
= resp
.getWriter();out
.write(new ObjectMapper().writeValueAsString(RespBean
.ok("注銷成功!")));out
.flush();out
.close();}}).permitAll();http
.cors().disable();http
.csrf().disable();}@Overridepublic void configure(WebSecurity web
) {web
.ignoring().antMatchers(HttpMethod
.OPTIONS
, "/**");}
}
四、mapper層
mapper下的StudentMapper.java
public interface StudentMapper {Student
loadUserBySno(String sno
);
}
resource下的StudentMapper.xml**
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jxnu.os.mapper.StudentMapper"><resultMap id="BaseResultMap" type="com.jxnu.os.model.Student"><id column="id" property="id" jdbcType="INTEGER"/><result column="username" property="username" jdbcType="VARCHAR"/><result column="sno" property="sno" jdbcType="VARCHAR"/><result column="s_sex" property="s_sex" jdbcType="CHAR"/><result column="t_id" property="t_id" jdbcType="INTEGER"/><result column="password" property="password" jdbcType="VARCHAR"/></resultMap><select id="loadUserByUsername" resultMap="BaseResultMap">select * from student where username=#{username}
</select></mapper>
五、model層
model下的Student.java
注意一定要implements UserDetails
public class Student implements UserDetails {
private Integer id
;private String username
;private String password
;public Integer
getId() {return id
;}public void setId(Integer id
) {this.id
= id
;}private Collection
<? extends GrantedAuthority> authorities
;public void setUsername(String username
) {this.username
= username
;}public void setPassword(String password
) {this.password
= password
;}public void setAuthorities(Collection
<? extends GrantedAuthority> authorities
) {this.authorities
= authorities
;}@Overridepublic Collection
<? extends GrantedAuthority> getAuthorities() {return this.authorities
;}@Overridepublic String
getPassword() {return this.password
;}@Overridepublic String
getUsername() {return this.username
;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;}
}
六、service層
service下的StudentService.java
@Service
public class StudentService implements UserDetailsService {@AutowiredStudentMapper studentMapper
;@Overridepublic UserDetails
loadUserByUsername(String username
) throws UsernameNotFoundException
{Student student
= studentMapper
.loadUserBySno(username
);if (student
== null
) {throw new UsernameNotFoundException("用戶不存在");}return student
;}
}
總結
以上是生活随笔為你收集整理的SpringBoot集成Spring Security(一)登录注销的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。