• 首页
  • 粮食
  • 蔬菜
  • 果品
  • 水产
  • 酒水
  • 饮料
  • 茶叶
  • 畜禽
  • 食用油
  • 资讯
logo
  • 首页>
  • 粮食 >
  • 正文

Spring Boot的安全配置(三)

2023-04-06 13:27:21 来源:腾讯云

JWT

JWT(JSON Web Token)是一种用于在网络中传输安全信息的开放标准(RFC 7519)。它可以在各个服务之间安全地传递用户认证信息,因为它使用数字签名来验证信息的真实性和完整性。

JWT有三个部分,每个部分用点(.)分隔:


(资料图片)

Header:通常包含JWT使用的签名算法和令牌类型。Payload:包含有关用户或其他主题的声明信息。声明是有关实体(通常是用户)和其他数据的JSON对象。声明被编码为JSON,然后使用Base64 URL编码。Signature:用于验证消息是否未被篡改并且来自预期的发送者。签名由使用Header中指定的算法和秘钥对Header和Payload进行加密产生。

在Spring Boot中,您可以使用Spring Security和jjwt库来实现JWT的认证和授权。下面是一个使用JWT的示例:

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Value("${jwt.secret}")    private String jwtSecret;    @Override    protected void configure(HttpSecurity http) throws Exception {        http.csrf().disable()            .authorizeRequests()            .antMatchers(HttpMethod.POST, "/api/authenticate").permitAll()            .anyRequest().authenticated()            .and()            .addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtSecret))            .addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtSecret))            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);    }    @Override    public void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.authenticationProvider(new JwtAuthenticationProvider(jwtSecret));    }}

在上面的示例中,SecurityConfig类继承了WebSecurityConfigurerAdapter并使用了@EnableWebSecurity注解启用Spring Security。configure()方法使用HttpSecurity对象来配置HTTP请求的安全性。.csrf().disable()禁用了CSRF保护。.authorizeRequests()表示进行授权请求。.antMatchers(HttpMethod.POST, "/api/authenticate").permitAll()表示允许POST请求到/api/authenticate路径。.anyRequest().authenticated()表示要求所有其他请求都需要身份验证。.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtSecret))和.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtSecret))分别添加JWT认证和授权过滤器。.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)指定了会话管理策略。

configure()方法中还有一个configure(AuthenticationManagerBuilder auth)方法,它使用JwtAuthenticationProvider类配置身份验证。在这里,jwtSecret被注入到JwtAuthenticationProvider构造函数中,以便在认证过程中使用。

下面是JwtAuthenticationFilter和JwtAuthorizationFilter的实现:

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {    private final AuthenticationManager authenticationManager;    private final String jwtSecret;    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, String jwtSecret) {        this.authenticationManager = authenticationManager;        this.jwtSecret = jwtSecret;        setFilterProcessesUrl("/api/authenticate");    }    @Override    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {        try {            LoginRequest loginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginRequest.class);            Authentication authentication = new UsernamePasswordAuthenticationToken(                    loginRequest.getUsername(),                    loginRequest.getPassword()            );            return authenticationManager.authenticate(authentication);        } catch (IOException e) {            throw new RuntimeException(e);        }    }    @Override    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) {        UserPrincipal userPrincipal = (UserPrincipal) authResult.getPrincipal();        String token = Jwts.builder()                .setSubject(userPrincipal.getUsername())                .setIssuedAt(new Date())                .setExpiration(new Date(System.currentTimeMillis() + 864000000))                .signWith(SignatureAlgorithm.HS512, jwtSecret)                .compact();        response.addHeader("Authorization", "Bearer " + token);    }}

JwtAuthenticationFilter类继承了UsernamePasswordAuthenticationFilter类,它用于处理基于用户名和密码的身份验证。它还使用AuthenticationManager来验证用户名和密码是否正确。jwtSecret在构造函数中被注入,用于生成JWT令牌。

在attemptAuthentication()方法中,LoginRequest对象被反序列化为从请求中获取的用户名和密码。这些值被封装到UsernamePasswordAuthenticationToken中,并传递给AuthenticationManager以验证用户身份。

在身份验证成功后,successfulAuthentication()方法被调用。在这里,UserPrincipal对象被从Authentication对象中获取,然后使用Jwts类生成JWT令牌。setSubject()方法将用户名设置为JWT主题。setIssuedAt()方法设置JWT令牌的发行时间。setExpiration()方法设置JWT令牌的到期时间。signWith()方法使用HS512算法和jwtSecret密钥对JWT令牌进行签名。最后,JWT令牌被添加到响应标头中。

下面是JwtAuthorizationFilter的实现:

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {    private final String jwtSecret;    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, String jwtSecret) {        super(authenticationManager);        this.jwtSecret = jwtSecret;    }    @Override    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {        String authorizationHeader = request.getHeader("Authorization");        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {            chain.doFilter(request, response);            return;        }        String token = authorizationHeader.replace("Bearer ", "");        try {            Jws claimsJws = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);            String username = claimsJws.getBody().getSubject();            List authorities = (List) claimsJws.getBody().get("authorities");            List grantedAuthorities = authorities.stream()                    .map(SimpleGrantedAuthority::new)                    .collect(Collectors.toList());            Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);            SecurityContextHolder.getContext().setAuthentication(authentication);            chain.doFilter(request, response);        } catch (JwtException e) {            response.setStatus(HttpStatus.UNAUTHORIZED.value());        }    }}

JwtAuthorizationFilter类继承了BasicAuthenticationFilter类,并覆盖了doFilterInternal()方法。在这个方法中,请求头中的Authorization标头被解析,如果它不是以Bearer开头,则直接传递给过滤器链。否则,从令牌中解析出主题(用户名)和授权信息,然后创建一个包含用户身份验证和授权信息的Authentication对象,并将其设置到SecurityContextHolder中。

如果JWT令牌无效,JwtException将被抛出,并返回HTTP 401未经授权的错误。

关键词:

    为您推荐

  • Spring Boot的安全配置(三)

    粮食2023-04-06
  • 【环球新视野】用鲜花代替烧纸 时空信箱传递思念 低碳环保文明祭祀成风尚

    粮食2023-04-06
  • 天天快看点丨签订劳动合同注意事项有什么?劳动合同是为了保障劳动者的权益吗?

    粮食2023-04-06
  • 布罗格登:进入季后赛要确保健康 剩下两场常规赛也要强势终结|每日消息

    粮食2023-04-06
  • 德权威研究机构上调今年德国经济增长预期-世界新视野

    粮食2023-04-06
  • 环球最资讯丨财务管理存在的问题及对策论文选什么企业好_财务管理存在的问题及对策论文

    粮食2023-04-06
  • 焦点快播:赠人玫瑰 手有余香——记益阳长春经开区阳光小院“活雷锋”龚孟希

    粮食2023-04-06
  • 降妖秘境攻略大全(降妖秘境攻略)

    粮食2023-04-06
  • 天天微速讯:矣的拼音(矣的拼音和意思)

    粮食2023-04-05
  • 券商经纪业务风光不再,21家公司去年收入整体下滑16%

    粮食2023-04-05
  • 即时焦点:1克拉等于多少克_1克拉是多少克

    粮食2023-04-05
  • 环球时讯:有友食品去年营收净利双降,泡椒凤爪销量大幅下降28%

    粮食2023-04-05
  • 即时:喜大普奔!印度决定使用卢比进行贸易,为何各国纷纷去美元化?

    粮食2023-04-05
  • 美议员:美国硅谷银行倒闭带来的后果远未结束

    粮食2023-04-05
  • 全球即时:vue面试题八股文简答大全 让你更加轻松的回答面试官的vue面试题

    粮食2023-04-05
  • 特朗普受刑事指控 美国政治极化加剧 民意更分裂:全球新视野

    粮食2023-04-05
  • 以实招长效治理经营性自建房:环球即时

    粮食2023-04-05
  • 宁化县气象台发布雷电黄色预警【Ⅲ级/较重】

    粮食2023-04-05
  • 西部第5的位置成了烫手山芋,谁都不愿意首轮面对太阳!|全球聚看点

    粮食2023-04-05
  • 上犹县气象台发布雷电黄色预警信号【III级/较重】

    粮食2023-04-04

果品

  • 北京2022年冬奥会、冬残奥会奖牌“同心”正式发布
  • 冬奥故事会丨一图了解冬奥会历届奖牌
  • 同心筑梦向未来——写在北京冬奥会开幕倒计时100天之际
  • 外交部:美国针对亚裔仇恨犯罪数字令人痛心

蔬菜

  • 说好“一梯一户”却成了“两梯两户”,买方能否解除合同?
  • 更高水平开放合作助力中国东盟经贸发展迎新机遇
  • 9被告人犯侵犯著作权罪被判刑罚
  • 玉渊谭天丨中美再通话,“建设性”很重要
  • 环球时报社评:中美经贸需要建设性对话
  • 俄媒:莫斯科扩大新冠感染新疗法试点范围
  • 冰雪之约 中国之邀 | 追赶的勇气
  • 中国第20批赴黎维和建筑工兵分队完成“VA-2”道路排水系统修缮任务
  • 中国常驻联合国代表团举办恢复联合国合法席位50周年图片展
  • 美专家认为三大原因导致美国供应链危机

Copyright   2015-2022 食品头条网 版权所有  备案号:沪ICP备2022005074号-20   联系邮箱:58 55 97 3@qq.com