鉴于:
spring+上的项目kotlin。实现了access_token通过数据库并使用它访问资源。
一个任务:
为通过浏览器中的登录表单登录的用户实现访问资源的能力。
问题:
只有一种授权方法有效。如果添加注释@EnableResourceServer,则带有令牌的访问方法有效。在浏览器中请求任何页面时,它只会显示“未经授权”错误,包括。在地址/login。如果您/login使用附加的令牌登录,它将显示404. 如果注释@EnableResourceServer被删除,则可以通过浏览器中的登录表单访问并获取令牌,但所有带有令牌的请求都将重定向到/login,即 令牌不被接受。
问题:
如何让它发挥作用?
从理论上讲,您需要在这里写一些东西,但是几个小时的谷歌搜索并没有让您了解到底是什么:
@Configuration
@EnableWebSecurity
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
class WebSecurityConfiguration : WebSecurityConfigurerAdapter() {
@Bean
fun passwordEncoder() = BCryptPasswordEncoder()
@Bean
fun authenticationProvider(): DaoAuthenticationProvider {
val authenticationProvider = DaoAuthenticationProvider()
authenticationProvider.setUserDetailsService(userDetailsService)
authenticationProvider.setPasswordEncoder(passwordEncoder())
return authenticationProvider
}
@Bean
override fun authenticationManagerBean(): AuthenticationManager {
return super.authenticationManagerBean()
}
@Autowired
lateinit var userDetailsService: UserServiceImpl
@Autowired
fun configureGlobal(auth: AuthenticationManagerBuilder) {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.authenticationProvider(authenticationProvider())
}
override fun configure(http: HttpSecurity) {
http
.csrf().disable()
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin().permitAll()
}
}
附加信息:
链接到整个项目GitHub:https ://github.com/mohaxspb/springSecurityExample/tree/v0.0.1
要开始工作,您需要在带有密码postgresql的用户名下安装并创建一个名称的数据库- 然后,在启动时,将在数据库中创建一个包含用户的表,并在那里添加一个用户,您可以在该表下可以使用登录名和密码登录。要获取令牌,您需要指定client_id :和client_secret : (该数据也在服务器启动时写入数据库)postgrestesttestspringbootdbtest@test.rupasswordclient_idclient_secret
问题解决了。它包括以下事实:当
@EnableResourceServer为每个请求向过滤器链添加注释时,添加了 aOAuth2AuthenticationProcessingFilter,在默认情况下,Cookie通过登录表单进入时使用的帮助明确禁止身份验证的设置是启用。另一方面,如果注释被删除
@EnableResourceServer,那么过滤器OAuth2AuthenticationProcessingFilter将不会被添加,并且 spring 将不知道有必要通过尝试使用令牌进行身份验证来响应带有令牌的请求。最后,我这样做了:
删除了注释
@EnableResourceServer。为每个请求手动添加
OAuth2AuthenticationProcessingFilter到过滤器链中,向它指示可以使用身份验证跳过请求Cookie此过滤器设置
AuthenticationManager类型OAuth2AuthenticationManagerOAuth2AuthenticationManager是一个附加的AuthenticationManager,它传递了一个实现ClientDetailsService(负责提供有关客户端应用程序的数据以进行授权)和一个ResourceServerTokenServices变成具有类型access_token的对象的实现AuthenticationOAuth2Authentication因为 spring需要知道哪个是
AuthenticationManager主要的,需要用注解标记默认@Primary因此,当 spring 在请求中没有找到 cookie 或 token 时,它会重定向到登录页面。输入数据后,它会在浏览器中设置一个 cookie 并使用它验证请求。如果请求中有令牌,则触发添加的过滤器并尝试使用令牌对请求进行身份验证。如果成功,将身份验证设置为
SecurityContext。结果,实现
WebSecurityConfigurerAdapter如下所示:v0.03 标签下仓库中的所有代码
您可以通过正确实现
ResourceServerConfigurerAdapter和返回来缩短代码@EnableResourceServer。如果它有效,我会更新答案。