当前位置: 首页 > news >正文

环球网站建设建网站的公司

环球网站建设,建网站的公司,常州金坛网站建设,整合营销方案案例目录标题原理架构图demo的项目结构JwtTokenUtilRestAuthenticationEntryPoint 和 RestfulAccessDeniedHandlerMyUserDetailsServiceJwtAuthenticationTokenFilterSecurityConfigControllerPostman 测试为了方便#xff0c;未采用是从数据库读取的方式。工具类都是别人那偷的未采用是从数据库读取的方式。工具类都是别人那偷的滑稽。原理架构图 demo的项目结构 JwtTokenUtil : JwtToken生成的工具类RestAuthenticationEntryPoint : 当未登录或者token失效访问接口时自定义的返回结果RestfulAccessDeniedHandler : 当访问接口没有权限时自定义的返回结果JwtAuthenticationTokenFilter : JWT登录授权过滤器SecurityConfigSpringSecurity 的配置类User 实现 UserDetails 接口 主要功能是 保存用户的账号密码以及角色列表MyUserDetailsService实现了 UserDetailsService 接口的 loadUserByUsername 方法 主要是进行登录信息验证在输入账户密码进行登录的时候会进入这个类进行验证信息。 由于类比较多一般建议创建的流程 1、创建 JwtTokenUtil 2、创建 RestAuthenticationEntryPoint 和 RestfulAccessDeniedHandler 3、创建 MyUserDetailsService 4、创建 JwtAuthenticationTokenFilter 5、配置 Security信息 SecurityConfig JwtTokenUtil import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component;import java.util.Date; import java.util.HashMap; import java.util.Map;/*** Description: JwtToken生成的工具类* Author: zlf* Date: 2021/3/30*/ Component public class JwtTokenUtil {private static final Logger LOGGER LoggerFactory.getLogger(JwtTokenUtil.class);private static final String CLAIM_KEY_USERNAME sub;private static final String CLAIM_KEY_CREATED created;Value(${jwt.secret})private String secret;Value(${jwt.expiration})private Long expiration;/*** 根据负责生成JWT的token*/private String generateToken(MapString, Object claims) {return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()).signWith(SignatureAlgorithm.HS512, secret).compact();}/*** 从token中获取JWT中的负载*/private Claims getClaimsFromToken(String token) {Claims claims null;try {claims Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();} catch (Exception e) {LOGGER.info(JWT格式验证失败:{},token);}return claims;}/*** 生成token的过期时间*/private Date generateExpirationDate() {return new Date(System.currentTimeMillis() expiration * 1000);}/*** 从token中获取登录用户名*/public String getUserNameFromToken(String token) {String username;try {Claims claims getClaimsFromToken(token);username claims.getSubject();} catch (Exception e) {username null;}return username;}/*** 验证token是否还有效** param token 客户端传入的token* param userDetails 从数据库中查询出来的用户信息*/public boolean validateToken(String token, UserDetails userDetails) {String username getUserNameFromToken(token);return username.equals(userDetails.getUsername()) !isTokenExpired(token);}/*** 判断token是否已经失效*/private boolean isTokenExpired(String token) {Date expiredDate getExpiredDateFromToken(token);return expiredDate.before(new Date());}/*** 从token中获取过期时间*/private Date getExpiredDateFromToken(String token) {Claims claims getClaimsFromToken(token);return claims.getExpiration();}/*** 根据用户信息生成token*/public String generateToken(UserDetails userDetails) {MapString, Object claims new HashMap();claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());claims.put(CLAIM_KEY_CREATED, new Date());return generateToken(claims);}/*** 判断token是否可以被刷新*/public boolean canRefresh(String token) {return !isTokenExpired(token);}/*** 刷新token*/public String refreshToken(String token) {Claims claims getClaimsFromToken(token);claims.put(CLAIM_KEY_CREATED, new Date());return generateToken(claims);} }RestAuthenticationEntryPoint 和 RestfulAccessDeniedHandler import cn.hutool.json.JSONUtil; import com.zlf.Api.CommonResult; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;/** * Description: 当未登录或者token失效访问接口时自定义的返回结果 * Author: zlf * Date: 2021/3/30 */ Component public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {System.out.println(--- --- 未登录);response.setCharacterEncoding(UTF-8);response.setContentType(application/json);response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(失败)));response.getWriter().flush();} }import cn.hutool.json.JSONUtil; import com.zlf.Api.CommonResult; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;/** * Description: 当访问接口没有权限时自定义的返回结果 * Author: zlf * Date: 2021/3/30 */ Component public class RestfulAccessDeniedHandler implements AccessDeniedHandler {Overridepublic void handle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException e) throws IOException, ServletException {response.setCharacterEncoding(UTF-8);response.setContentType(application/json);response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));response.getWriter().flush();} }MyUserDetailsService import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component;import java.util.ArrayList; import java.util.List;/*** Created with IntelliJ IDEA.** Auther: zlf* Date: 2021/03/30/23:38* Description:*/ Component public class MyUserDetailsService implements UserDetailsService {Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 这边可以通过username去获取数据库中的用户信息 如果没有抛出异常ListGrantedAuthority authorityList new ArrayList();/* 此处查询数据库得到角色权限列表这里可以用Redis缓存以增加查询速度 */System.out.println(--- ---- 判断);authorityList.add(new SimpleGrantedAuthority(ROLE_USER)); // 角色 需要以 ROLE_ 开头return new org.springframework.security.core.userdetails.User(username, new BCryptPasswordEncoder().encode(123456), authorityList);} }JwtAuthenticationTokenFilter import com.zlf.utils.JwtTokenUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List;/** * Description: JWT登录授权过滤器 * Author: zlf * Date: 2021/3/30 */ Component Slf4j public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {//Autowired//private UserDetailsService userDetailsService;Autowiredprivate JwtTokenUtil jwtTokenUtil;Value(${jwt.tokenHeader})private String tokenHeader;Value(${jwt.tokenHead})private String tokenHead;Autowiredprivate MyUserDetailsService userDetailsService;Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws ServletException, IOException {String authHeader request.getHeader(this.tokenHeader);if (authHeader ! null authHeader.startsWith(this.tokenHead)) {String authToken authHeader.substring(this.tokenHead.length());// The part after Bearer String username jwtTokenUtil.getUserNameFromToken(authToken);log.info(checking username:{}, username);if (username ! null SecurityContextHolder.getContext().getAuthentication() null) {UserDetails userDetails userDetailsService.loadUserByUsername(username);if (jwtTokenUtil.validateToken(authToken, userDetails)) {UsernamePasswordAuthenticationToken authentication new UsernamePasswordAuthenticationToken(userDetails, new BCryptPasswordEncoder().encode(123456), userDetails.getAuthorities());authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));log.info(authenticated user:{}, username);SecurityContextHolder.getContext().setAuthentication(authentication);}}}chain.doFilter(request, response);}// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // ListGrantedAuthority authorityList new ArrayList(); // /* 此处查询数据库得到角色权限列表这里可以用Redis缓存以增加查询速度 */ // authorityList.add(new SimpleGrantedAuthority(ROLE_USER)); // 角色 需要以 ROLE_ 开头 // return new org.springframework.security.core.userdetails.User(username, 123456, true, true, // true, true, authorityList); // } }SecurityConfig import com.zlf.component.JwtAuthenticationTokenFilter; import com.zlf.component.MyUserDetailsService; import com.zlf.component.RestAuthenticationEntryPoint; import com.zlf.component.RestfulAccessDeniedHandler; import com.zlf.entity.model.Admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;/*** Created with IntelliJ IDEA.** Auther: zlf* Date: 2021/03/30/20:45* Description:*/ EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {Autowiredprivate MyUserDetailsService userDetailsService;Autowiredprivate RestfulAccessDeniedHandler restfulAccessDeniedHandler;Autowiredprivate RestAuthenticationEntryPoint restAuthenticationEntryPoint;Autowiredprivate JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.csrf()// 由于使用的是JWT我们这里不需要csrf.disable().sessionManagement()// 基于token所以不需要session.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问/,/*.html,/favicon.ico,/**/*.html,/**/*.css,/**/*.js,/swagger-resources/**,/v2/api-docs/**).permitAll().antMatchers(/admin/login, /register)// 对登录注册要允许匿名访问.permitAll().antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求.permitAll() // .antMatchers(/**)//测试时全部运行访问 // .permitAll().anyRequest()// 除上面外的所有请求全部需要鉴权认证.authenticated();// 禁用缓存httpSecurity.headers().cacheControl();// 添加JWT filterhttpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);//添加自定义未授权和未登录结果返回httpSecurity.exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler).authenticationEntryPoint(restAuthenticationEntryPoint);}Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());}// Bean // public PasswordEncoder passwordEncoder() { // return new BCryptPasswordEncoder(); // }// Bean // public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){ // return new JwtAuthenticationTokenFilter(); // }BeanOverridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();} }Controller import com.zlf.entity.User; import com.zlf.utils.JwtTokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map;/*** Created with IntelliJ IDEA.** Auther: zlf* Date: 2021/03/30/23:15* Description:*/ RestController public class LoginController {Autowiredprivate JwtTokenUtil jwtTokenUtil;Value(${jwt.tokenHead})private String tokenHead;PostMapping(/admin/login)public String login(RequestBody User user, HttpServletRequest request) {/* 在这里验证用户名和密码验证成功则生成token返回 */System.out.println(--- -- -login);System.out.println(user);return tokenHead jwtTokenUtil.generateToken(user); // 生成 Token返回给客户端}PreAuthorize(hasAnyRole(USER)) // 对单个方法进行权限控制GetMapping(/me)public String me() {// 从上下文中获取 UserDetailsUserDetails userDetails (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();return userDetails.getUsername() , userDetails.getPassword();} }Postman 测试 我们将登录获取到的 Token 放到请求头中。 最后放出 JWT key的配置 # 自定义jwt key jwt:tokenHeader: Authorization #JWT存储的请求头secret: mySecret #JWT加解密使用的密钥expiration: 604800 #JWT的超期限时间(60*60*24)tokenHead: Bearer #JWT负载中拿到开头依赖 !--Hutool Java工具包--dependencygroupIdcn.hutool/groupIdartifactIdhutool-all/artifactIdversion4.5.7/version/dependency!--JWT(Json Web Token)登录支持--dependencygroupIdio.jsonwebtoken/groupIdartifactIdjjwt/artifactIdversion0.9.0/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependency
http://www.pierceye.com/news/759932/

相关文章:

  • 企业网站的规划与建设纯静态网站开发
  • 静海集团网站建设网址收录查询
  • 怎样做网站的外链怎么做自己的网站
  • nas 建网站asp.net 做网站源代码
  • 做网站的详细步骤叫别人做网站权重被转移了
  • 做网站好还是网店做网站是怎样赚钱的
  • 国内网站 备案北京模板网站建站
  • 怎么建立网站?婚纱网站策划书模板下载
  • 接单子做网站词类似酷家乐做庭院的网站
  • 道路建设网站专题推广做黄页网站
  • 做展柜平时在哪里网站推广青岛原创工程设计有限公司
  • 网站建设加网络营销营销网站有多种类型
  • 深圳网站网页制作公司深圳品牌网站建设公司有哪些
  • 网站建设中 windows网站后台用什么做
  • 外贸营销型网站建站怎么做便民信息网站
  • 事业单位门户网站建设的建议大连建设工程信息网华宇凤凰城东侧市政管网配套工程
  • 上海网站建设开发哪亚马逊官网首页中国
  • 常德网站建设套餐报价英文网站字体大小
  • 橙色网站logo 配色播放器网站怎么做
  • dw网站制作怎样做网站xml
  • 房屋租赁网站开发意义新网站如何做排名
  • 钉钉如何做自己的网站银川企业网站建设
  • 做游戏女角色去衣的网站网站建设及售后服务的说明书
  • 微网站下载资料怎么做网站开发毕业设计任务书怎么写
  • ckplayer网站根目录泉州 网站制作
  • 中国建设银行网站江苏分行帮别人做网站收多少钱合适
  • 公司该建哪种网站带有互动的网站开发
  • 怎样进入谷歌网站怎么做一个简易网站
  • 邯郸网站优化公司集团公司简介模板
  • 网站的需求分析怎么写文山州住房建设网站