spring boot整合scurity做简单的登录校验的实现

网友投稿 769 2023-06-14

spring boot整合scurity做简单的登录校验的实现

spring boot整合scurity做简单的登录校验的实现

开发环境:springboot

maven引入:

org.springframework.security.oauth

spring-security-oauth2

2.2.1.RELEASE

org.springframework.security

spring-security-jwt

1.0.10.RELEASE

1、先在数据库创建用户表,用户名为username,密码名为password。下面是我用户表的实体

private Integer id;

/**

* 昵称

*/

private String name;

/**

* 职位

*/

private String code;

/**

* 密码

*/

private String passwd;

/**

* 用户名

*/

private String username;

/**

* 手机号

*/

private String phone;

/**

* 创建时间

*/

private Date createdTime;

2、看项目是JPA、还是mybatis。我这边项目使用的是mybatis。需要有一个方法通过用户名获取用户信息。

3、创建一个用户验证类实现 UserDetails 继承用户实体

public class SecurityUser extends SysUser implements UserDetails {

private static final long serialVersihttp://ongUID = 1l;

public SecurityUser(SysUser sysUser) {

if (null != sysUser) {

this.setCode(sysUser.getCode());

this.http://setCreatedTime(sysUser.getCreatedTime());

this.setId(sysUser.getId());

this.setName(sysUser.getName());

this.setPasswd(sysUser.getPasswd());

this.setPhone(sysUser.getPhone());

this.setUsername(sysUser.getUsername());

}

}

@Override

public Collection extends GrantedAuthority> getAuthorities() {

Collection authorities = new ArrayList<>();

String username = this.getUsername();

if (username != null) {

SimpleGrantedAuthority authority = new SimpleGrantedAuthority(username);

authorities.add(authority);

}

return authorities;

}

@Override

public String getPassword() {

return super.getPasswd();

}

//账户是否未过期,过期无法验证

@Override

public boolean isAccountNonExpired() {

return true;

}

//指定用户是否解锁,锁定的用户无法进行身份验证

@Override

public boolean isAccountNonLockhttp://ed() {

return true;

}

//指示是否已过期的用户的凭据(密码),过期的凭据防止认证

@Override

public boolean isCredentialsNonExpired() {

return true;

}

//是否可用 ,禁用的用户不能身份验证

@Override

public boolean isEnabled() {

return true;

}

}

4、重点!创建一个scurity config配置

@Configuration

@EnableWebSecurity

public class UiSecurityConfig extends WebSecurityConfigurerAdapter {

private static final Logger logger = LoggerFactory.getLogger(UiSecurityConfig.class);

@Override

protected void configure(HttpSecurity http) throws Exception { //配置策略

http.csrf().disable();

http.authorizeRequests().

antMatchers("/static/**").permitAll().anyRequest().authenticated().

and().formLogin().loginPage("/login").permitAll().successHandler(loginSuccessHandler()).

and().logout().permitAll().invalidateHttpSession(true).

deleteCookies("jsESSIONID").logoutSuccessHandler(logoutSuccessHandler()).

and().sessionManagement().maximumSessions(10).expiredUrl("/login");

}

@Bean

public BCryptPasswordEncoder passwordEncoder() { //密码加密

return new BCryptPasswordEncoder(4);

}

@Bean

public LogoutSuccessHandler logoutSuccessHandler() { //登出处理

return new LogoutSuccessHandler() {

@Override

public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

try {

SecurityUser user = (SecurityUser) authentication.getPrincipal();

logger.info("USER : " + user.getUsername() + " LOGOUT SUCCESS ! ");

} catch (Exception e) {

logger.info("LOGOUT EXCEPTION , e : " + e.getMessage());

}

httpServletResponse.sendRedirect("/login");

}

};

}

@Bean

public SavedRequestAwareAuthenticationSuccessHandler loginSuccessHandler() { //登入处理

return new SavedRequestAwareAuthenticationSuccessHandler() {

@Override

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

SysUser userDetails = (SysUser) authentication.getPrincipal();

logger.info("USER : " + userDetails.getUsername() + " LOGIN SUCCESS ! ");

// 登录成功后重定向路径

response.sendRedirect("/");

}

};

}

//用户登录实现

@Bean

public UserDetailsService userDetailsService() {

return new UserDetailsService() {

@Autowired

private SysUserDao sysUserDao;//这里是引入数据库连接dao

@Override

public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

SysUser userNmae = new SysUser();

userNmae.setUsername(s);

List listUser = sysUserDao.queryAll(userNmae);//通过用户名获取个用户信息

SysUser user = null;

if (listUser.size() > 0) {

user = listUser.get(0);

}

if (user == null) throw new UsernameNotFoundException("Username " + s + " not found");

return new SecurityUser(user);

}

};

}

}

5、基础工作准备完成开始写controller

@Controller

public class LoginController {

@Resource

private SessionTool sessionTool;

// 获取登录页面

@RequestMapping(value = "/login", method = RequestMethod.GET)

public String login() {

return "login";

}

@RequestMapping("/")

public String login(ModelMap map){

SysUser sysUser = sessionTool.getUser();

map.addAttribute("sysUser", sysUser);

return "index";

}

}

6、从session获取用户信息

@Component

public class SessionTool {

public SysUser getUser() { //为了session从获取用户信息,可以配置如下

SysUser user = new SysUser();

SecurityContext ctx = SecurityContextHolder.getContext();

Authentication auth = ctx.getAuthentication();

if (auth.getPrincipal() instanceof UserDetails) user = (SysUser) auth.getPrincipal();

return user;

}

public HttpServletRequest getRequest() {

return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

}

}

7、login.html页面(登录路径为login 请求方式为post,scurity自带的登录路径)

用户名 :

密码 :

总结一下思路:

引入依赖包-》创建用户表-》创建用户表数据库查询接口-》创建用户校验类实现UserDetails接口-》创建scurity配置类继承 WebSecurityConfigurerAdapter 方法configure为配置校验策略-》创建controller配置登录页面跳转接口-》创建登陆页面用户名必须为username 密码为password 登录路径为'/login' 请求方式为post

由于scurity配置的密码检验是加密的为了测试可以在Test模块中获取加密后的密码然后存到用户表的password字段中。

@Test

public void encoder() {

String password = "123123";

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);

String enPassword = encoder.encode(password);

System.out.println(enPassword);

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:IntelliJ Idea 2020.1 正式发布,官方支持中文(必看)
下一篇:详解基于Mybatis
相关文章

 发表评论

暂时没有评论,来抢沙发吧~