当前位置: 首页 > 知识库问答 >
问题:

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

潘翰藻
2023-03-14

我想保护Spring Boot API,使它只对具有有效API密钥和秘密的客户机是可访问的。但是,由于所有数据都是匿名的,程序内部没有身份验证(使用用户名和密码的标准登录)。我试图实现的只是所有API请求都可以仅用于特定的第三方前端

共有1个答案

房新翰
2023-03-14

创建一个筛选器来抓取用于身份验证的头。

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";
    }

}

在Web安全配置中配置筛选器。

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();
    }

}
 类似资料:
  • 我试图保护Spring BootAPIendpoint。我希望只传递api密钥和秘密作为头的一部分来调用api。我尝试了这个链接中发布的代码。但是在头中使用授权调用api时拒绝访问。使用API key和secret保护Spring Boot API我想知道我应该作为头部的一部分传递什么,这样我就可以从API获得成功的响应。我做了以下步骤:我在application.properties中添加了以下

  • OAuth 2.0 资源所有者密码授权 允许一个客户端发送用户名和密码到令牌服务并获得一个表示该用户访问令牌。 (OAuth 2.0) 规范 建议仅对“受信任”的应用程序使用资源所有者密码授权。一般来说,当你想要验证一个用户并请求访问令牌的时候,使用交互式 OpenID Connect 流通常会更好。 不过,这个授权类型允许我们在 IdentityServer 快速入门中引入 用户 的概念,这是我

  • Swagger支持api密钥的安全性,但这似乎仅限于单个参数。 有没有办法定义一组参数(key和secret)作为请求中的参数? 或者,唯一的方法就是跳过安全方案,只将这些参数添加到每个请求中?

  • 嘿,我想使用Azure密钥库加密/解密我的数据库中的数据。我看到自己和其他人都在纠结的一个主要问题是如何保护程序中的访问id和密钥。我看到有人说,如果你没有一个原生的微软应用程序(我没有,我的应用程序运行在第三方linux服务器上),你可以获得一个证书来访问密钥库。在我掏出200美元购买之前,我想知道拥有该证书意味着即使证书被盗,攻击者也不能用它来访问密钥库,对吧?我的理解是证书只能在我的域上工作

  • 我得到异常“http://api.openweathermap.org/data/2.5/weather?q=sydney”。有人能帮忙怎么用吗。当我粘贴以下内容时,可以很好地使用web浏览器 我也试过下面的组合,但没有运气

  • 我遇到了许多API,它们为用户提供了一个API密钥和一个秘密。但我的问题是:两者之间有什么区别? 在我看来,一把钥匙就足够了。假设我有钥匙,只有我和服务器知道。我用这个键创建了一个HMAC哈希,并进行了一个API调用。在服务器上,我们再次创建HMAC哈希,并将其与发送的哈希进行比较。如果是相同的,则呼叫经过身份验证。 那为什么要用两把钥匙呢? 编辑:或者该API密钥用于查找API机密?