spring - 我可以使用 API 调用通过 Spring Security 对不同的应用程序进行身份验证吗?
问题描述
我正在涉足 Spring Boot。最终目标是创建一个简单的仪表板,提供关于部署在 Tomcat 上的另一个 Web 应用程序的统计信息和示例。API 调用。您还可以使用 API 通过 SOAP 进行身份验证,这是我目前想做的(通过 HTTPS)。我一直在寻找这样的 Spring Security 指南:https ://www.baeldung.com/spring-security-authentication-provider
我的主要问题是:Spring Security 是否适合我想要做的事情?根据上面的链接,我有以下代码:
@Component
public class CustomAuthenticationProvider
implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
try {
ApiAuthenticationServiceClient a = new ApiAuthenticationServiceClient();
a.authenticate(name, password);
//authentication successful return token
return new UsernamePasswordAuthenticationToken(
name, password, new ArrayList<>());
} catch(ApiAuthenticationException e) {
//Authentication failed return null
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(
UsernamePasswordAuthenticationToken.class);
}
}
我用这个来找错树了吗?这更多的是爱好/学习项目,所以如果我是,我总是可以放弃这个想法并尝试其他东西。
解决方案
这当然是解决它的一种方法。在您的示例中,假设您已配置httpBasic()
身份验证
@Override
protected void configure(HttpSecurity http) throws Exception {
http...
.httpBasic();
}
或formLogin()
认证
@Override
protected void configure(HttpSecurity http) throws Exception {
http...
.formLogin();
}
这些场景中的每一个都会在过滤器链中插入一个过滤器。这些过滤器将从标头 (http-basic) 或 HTTP 参数 (form-login) 中读取用户名和密码。它采用这些值并创建 UsernamePasswordAuthenticationToken 并调用您的自定义处理程序。
您也可以通过简单地实现过滤器来完全完成此操作而无需自定义身份验证提供程序
@Override
protected void configure(HttpSecurity http) throws Exception {
http...
.addFilter(new MyCustomFilter());
}
public static class MyCustomFilter extends OncePerRequestFilter {
public void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) {
if (<should we attempt authentication based on logic> {
try {
String username = ...
String password = ...
ApiAuthenticationServiceClient a = new ApiAuthenticationServiceClient();
a.authenticate(name, password);
//authentication successful return token
SecurityContextHolder
.getContext()
.setAuthentication(
new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>())
);
} catch(ApiAuthenticationException e) {
//Authentication failed maybe log it?
}
}
//continue
chain.doFilter(request, response);
}
给猫剥皮的上千种方法。你选择一个适合你的。身份验证提供程序方法有效,您只需要知道有一个过滤器可以UsernamePasswordAuthenticationToken
为您创建对象。如果您不配置这些过滤器,您将永远不会收到对您的身份验证提供程序的回调。
推荐阅读
- r - 在 R 中设置颜色条限制
- python - 当python没有返回时,如何访问另一个函数中的值?
- ios - SwiftUI:NavigationView/NavigationLink:启动并推送目的地?
- kentico - Kentico 13 上缺少字典
- javascript - 如何从 document.write 内的脚本访问 document.body
- mysql - 将数据帧转换为 SQL 时出错 - Pandas
- r - 为什么使用函数命名空间会大大增加开销?
- reactjs - React Native 项目 - 只有 15 个活跃用户的重要 Cloud Firestore 读取
- android - react-native:是否可以一直在后台录制视频?
- git - 使用 GitBash 时代理设置搞砸了