我正在尝试使用Spring boot设置授权服务器。
该服务器应该能够使用登录/密码表单和github(例如)授权用户。
我希望这张照片有助于更好地理解我想要什么。
登录表单示例:
要求:
我只能使用代码完成需求列表中的前3点:
@SpringBootApplication
@RestController
@Configuration
@Import(AuthorizationServerSecurityConfiguration.class)
public class SsoApplication extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(SsoApplication.class, args);
}
@GetMapping("/")
public Authentication me() {
return SecurityContextHolder.getContext().getAuthentication();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.oauth2Login();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("123")
.password(passwordEncoder().encode("123"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
}
完整的代码示例可以在githab上查看
作为检查项目3和4的客户,您可以使用带有设置的邮递员来获取令牌:
我未能实施:
postman控制台出现错误:
Invalid authorization code: 97477114b3ec3c53547d
我会很感激任何帮助。谢谢!
我找到了错误的原因。问题是Postman从授权服务器的github中截获了错误的代码,而不是客户端授权服务器所需的代码。
换句话说,问题出在postman中。为了进行正确的验证,您必须使用成熟的oaut2客户端。
你的代码对我很有效。
但是我在github中创建了自己的“OAuth应用程序”。然后用你的代码,我放入了我的Github应用程序:
主页URL:http://localhost:8080
授权回调URL:http://localhost:8080/login
并且在给按钮并允许应用程序使用github识别我之后,我已经返回了主
...
"authenticated": true,
"principal": {
"authorities": [
{
"authority": "ROLE_USER",
"attributes": {
"login": "xxx",
...
如您所见,您的Spring应用程序不是问题,我认为是您的github配置。
编辑:
在Postman控制台中,如果您将注释@EnableOAuth2Sso
放在配置SsoApplication
中,错误就会消失:
@SpringBootApplication
@RestController
@Configuration
@EnableOAuth2Sso
@Import(AuthorizationServerSecurityConfiguration.class)
public class SsoApplication extends WebSecurityConfigurerAdapter