我正在尝试实现我的第一个Spring引导应用程序,用keyclock保护。我在这两个方面都是新手,但我认为目前为止我做得还不错。我一直在看各种教程,但我最近使用的是
所以,我已经设置了一个正在运行的Spring启动/Hibernate应用程序(作为目前的概念证明)。所以,现在我想用keyclock来保护它。我拥有的是Controller.java
@Controller // This means that this class is a Controller
@RequestMapping(path="/test") // This means URL's start with /demo (after Application path)
public class MainController {
@Autowired
GemhMainRepository repository;
@Autowired
CompaniesRepository gsisCompanies;
@RequestMapping("/protected")
public String protectedHello() {
System.out.println("test"); return "Hello World, i was protected";
}}
Main.java
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })//do not create security credentials. we will use our own
public class Main {
@Bean
public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver(){
return new KeycloakSpringBootConfigResolver();
}
public static void main(String[] args) {
SpringApplication.run(GsisApi.class, args);
}
}
应用程序属性
server.port=8080
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://sqlHost:3306/Db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.show-sql=true
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
keycloak.auth-server-url=http://localhost:31063/auth
keycloak.realm=testRealm
keycloak.resource=test_client
keycloak.public-client=true
keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/test
keycloak.principal-attribute=preferred_username
SecurityConfig.java
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.anyRequest().authenticated()
;
}
}
当我从奇洛克那里得到一个代币的时候,这看起来很有效,
curl --data "grant_type=password&client_id=test_client&username=user&password=password&client_secret=xxx" 'http://localhost:31063/auth/realms/testRealm/protocol/openid-connect/token'
我跑步时确实有结果
curl localhost:8080/test/protected -H "Authorization: bearer xxxxxxx " --insecure
但是当我尝试在没有令牌的情况下使用它时,我什么也得不到。甚至不是我在屏幕上打印的消息。我想我需要收到 403 错误,以便通知用户他们必须使用一些 token.对吧?有什么帮助吗?谢谢
好的,看来我让它工作了。出于某种我无法理解的原因,遵循这些说明似乎可以解决问题。我创建了
MyAuthenticationEntryPoint.java
@ControllerAdvice
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
// 401
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
}
@ExceptionHandler (value = {AccessDeniedException.class})
public void commence(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {
// 403
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization Failed : " + accessDeniedException.getMessage());
}
@ExceptionHandler (value = {Exception.class})
public void commence(HttpServletRequest request, HttpServletResponse response,
Exception exception) throws IOException {
// 500
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error : " + exception.getMessage());
}
}
并将其添加到我的SecurityConfig.java中
http.exceptionHandling()
.authenticationEntryPoint(new MyAuthenticationEntryPoint());
正在制作
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/test/health/*").permitAll()
.anyRequest().authenticated()
;
http.exceptionHandling()
.authenticationEntryPoint(new MyAuthenticationEntryPoint());
}
}
同样通过添加 .antMatchers(“/test/health/*”).permitAll()
我可以调用 health 而无需任何凭据。
我对自己正在做的事情没有100%的信心。因此,如果您发现不对劲的地方,请告诉我。