使用API​​密钥和机密保护Spring Boot API

使用API​​密钥和机密保护Spring Boot API,第1张

使用API​​密钥和机密保护Spring Boot API

创建一个过滤器,以获取用于身份验证的标头。

import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;public class APIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {    private String principalRequestHeader;    public APIKeyAuthFilter(String principalRequestHeader) {        this.principalRequestHeader = principalRequestHeader;    }    @Override    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {        return request.getHeader(principalRequestHeader);    }    @Override    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {        return "N/A";    }}

在网络安全配置中配置过滤器。

import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.BadCredentialsException;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.Authentication;import org.springframework.security.core.AuthenticationException;@Configuration@EnableWebSecurity@Order(1)public class APISecurityConfig extends WebSecurityConfigurerAdapter {    @Value("${yourapp.http.auth-token-header-name}")    private String principalRequestHeader;    @Value("${yourapp.http.auth-token}")    private String principalRequestValue;    @Override    protected void configure(HttpSecurity httpSecurity) throws Exception {        APIKeyAuthFilter filter = new APIKeyAuthFilter(principalRequestHeader);        filter.setAuthenticationManager(new AuthenticationManager() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException {     String principal = (String) authentication.getPrincipal();     if (!principalRequestValue.equals(principal))     {         throw new BadCredentialsException("The API key was not found or not the expected value.");     }     authentication.setAuthenticated(true);     return authentication; }        });        httpSecurity. antMatcher("/api/**"). csrf().disable(). sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS). and().addFilter(filter).authorizeRequests().anyRequest().authenticated();    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5641426.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存