使用AuthToken架构保护用户帐号验证Cookie的安全性

在项目或者网站开发中,我们很多人很多时候喜欢使用微软的FormsAuthentication类的GetAuthCookie函数生成需要在访客客户端放置的帐号校验Cookie,这个本身没问题,但是很多人会被GetAuthCookie的userName参数误导,以为传递UserID或者UserName就很安全了.而实际上,Cookie本身并不安全,如果完整复制了校验Cookie,在Cookie的允许时间范围内,黑客完全可以使用该Cookie代表的帐号做各种危害网站和应用的事情,即使设定了Cookie的过期时间,但是如果完整复制该Cookie信息,由于站点的machineKey基本不会变化,每次基于特定用户的UserID和UserName生成的Cookie实际上一直不变,那么黑客只要保留了该全部Cookie的信息,就可以一直为所欲为,不受用户登录帐号和密码变更限制,比如校内曾经发生过xss脚本注入事件,导致很多用户丢失了日记照片.所以保护帐号校验Cookie很重要.
 
解决方案是避免使用UserID和UserName这种不会变化的字段做为验证Cookie的基础,我建议使用一种我称之为AuthToken的机制,意即验证Token,(token:标志,象征),AuthToken可以随每次用户通过登录页面登录变化,保证用户的顺畅使用,同时又避免无限期使用不变的验证Cookie导致的帐号被盗现象的发生.
 
下面来解释下AuthToken的运作模式,先上数据库设计图,大家看图理解.

 

 

这张表的字段分别是
UserID:用户标识
AuthToken:验证Token
SessionID:客户端SessionID
ExpireTime:绝对过期时间
 
请注意UserID和AuthToken为合并主键,这并不是错误,而是有意的设计,大家听我解释
首先每个客户端的浏览器我们都会获得一个SessionID,这个是肯定有的,而且同一台机器不同浏览

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security可以使用JWT(JSON Web Token)来验证用户的身份和权限。 1.添加JWT依赖项:在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2.创建JWT工具类:创建一个JWT工具类来生成和验证JWT。 ``` import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { private final String JWT_SECRET = "mysecretkey"; private final int JWT_EXPIRATION_MS = 86400000; public String generateJwtToken(Authentication authentication) { User user = (User) authentication.getPrincipal(); return Jwts.builder() .setSubject((user.getUsername())) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + JWT_EXPIRATION_MS)) .signWith(SignatureAlgorithm.HS512, JWT_SECRET) .compact(); } public boolean validateJwtToken(String authToken) { try { Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(authToken); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public String getUsernameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token) .getBody().getSubject(); } } ``` 3.创建JWT过滤器:创建一个JWT过滤器来验证JWT并设置用户的身份和权限。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.example.demo.security.services.UserDetailsServiceImpl; import io.jsonwebtoken.ExpiredJwtException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtAuthTokenFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { String jwt = parseJwt(request); if (jwt != null && jwtUtils.validateJwtToken(jwt)) { String username = jwtUtils.getUsernameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (Exception e) { logger.error("Cannot set user authentication: {}", e.getMessage()); } chain.doFilter(request, response); } private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if (headerAuth != null && headerAuth.startsWith("Bearer ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } } ``` 4.配置Spring Security:在Spring Security配置中添加JWT过滤器。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.example.demo.security.jwt.JwtAuthTokenFilter; import com.example.demo.security.services.UserDetailsServiceImpl; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( // securedEnabled = true, // jsr250Enabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthTokenFilter jwtAuthTokenFilter; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(bCryptPasswordEncoder); return authProvider; } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 现在,Spring Security将使用JWT来验证用户的身份和权限。您可以在需要身份验证和授权的端点上使用Spring Security注释,例如@PreAuthorize和@PostAuthorize。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值