![](/img/trans.png)
[英]Spring Security: Different authentication methods depending on entity
[英]Enable Spring Security authentication depending on client URL
我有一個用 Spring 制作的應用程序,它使用 JWT 身份驗證。
我想知道您是否有可能根據哪個客戶端訪問我的后端來發布路由,例如:
clientA:8080
- 允許/health
路由而無需身份驗證clientB:8081
- 在沒有 JWT 身份驗證的情況下不允許/health
路由。我試過這樣的事情:
http.authorizeRequests().antMatchers("http://clientA/health").permitAll()
但它沒有用。
我強烈建議不要使用這種不是強身份驗證機制的身份驗證。 但是,您可以像進行多重身份驗證一樣實現。 基本上你需要多個帶有requestMatcher 的WebSecurityConfigurerAdapter 。
這是一個快速示例(不要這樣做):
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfigurations {
@Configuration
@Order(1)
public static class NoAuth extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.requestMatcher(r -> r.getRequestURL().toString().startsWith("http://localhost:8081"))
.authorizeRequests()
.anyRequest().permitAll();
}
}
@Configuration
@Order(2)
public static class Auth extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
final byte[] salt = "random".getBytes(StandardCharsets.UTF_8);
KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256);
SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.decoder(NimbusJwtDecoder.withSecretKey(key).build());
}
}
}
應用配置:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public ServletWebServerFactory serverContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createConnector());
return tomcat;
}
private Connector createConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8081);
connector.setScheme("http");
connector.setSecure(false);
return connector;
}
}
控制器
@RestController
public class HealthApi {
@GetMapping("/health")
public String health() {
return "healthy";
}
}
你可以用 curl 測試一下:
curl -v localhost:8081/health
200 OK 健康
curl -v localhost:8080/health
401
curl -v -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.LUn3qZESwtUIbXrD3WSd3CNEOTwbKV9x2IahoLUCyAs" localhost:8080/health
200 OK 健康
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.