Spring boot 未找到Spring boot security oauth2授权\代码流登录页面

Spring boot 未找到Spring boot security oauth2授权\代码流登录页面,spring-boot,spring-security,oauth-2.0,spring-security-oauth2,Spring Boot,Spring Security,Oauth 2.0,Spring Security Oauth2,您好,我正在尝试使用spring security实现OAuth2,到目前为止,我已经成功地使用grant_type=password实现了OAuth2,我得到了令牌、时间、刷新令牌,并且资源得到了预期的保护 现在,我的下一步是使用authorization\u code+pkce实现 我遵循了这一点,当我用auth服务器详细信息替换所有客户端凭据时,我得到了http://localhost:8080/oauth/login未找到消息。请求是这样的http://localhost:8080/au

您好,我正在尝试使用spring security实现OAuth2,到目前为止,我已经成功地使用
grant_type=password
实现了OAuth2,我得到了
令牌、时间、刷新令牌
,并且资源得到了预期的保护

现在,我的下一步是使用
authorization\u code+pkce
实现

我遵循了这一点,当我用auth服务器详细信息替换所有客户端凭据时,我得到了
http://localhost:8080/oauth/login
未找到
消息。请求是这样的
http://localhost:8080/auth/oauth/authorize?client_id=SampleClientId&redirect_uri=http://localhost:8083/ui2/login&response_type=code&state=5ppnu6

我的配置和服务器文件如下所示,这是我第一次在服务器端实现oauth,所以我可能做的很不合理,请帮助我更正。
AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
BeansConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
ResourceServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
SecurityConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
UsersController.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
UserDetailsServiceImpl.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}
@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.init(passwordEncoder);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}
public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}
@Service(“userdetailssservice”)
公共类UserDetailsServiceImpl实现UserDetailsService{
私有静态最终记录器Logger=Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());
公共枚举角色{
用户,
调解人
管理
}
private final List users=new ArrayList();
公共用户详细信息服务impl(){
}
public void init(BCryptPasswordEncoder passwordEncoder){
add(newuserdetailsiml(“john”,passwordEncoder.encode(“doe”),buildUserAuthorities());
add(newuserdetailsiml(“哇”,passwordEncoder.encode(“宝贝”),buildmediatorauthorities());
}
私有列表BuildUserAuthories(){
最终列表authorityList=new ArrayList();
添加(新的SimpleGrantedAuthority(Role.USER.name());
返回权威列表;
}
私有列表buildModeratorAuthorities(){
最终列表authorityList=new ArrayList();
add(新的SimpleGrantedAuthority(Role.慢化剂.name());
返回权威列表;
}
@凌驾
public UserDetails loadUserByUsername(字符串s)引发UsernameNotFoundException{
for(userdetailsiml-details:users){
if(details.getUsername().equals)){
记录器。警告(“找到用户:+s”);
退货详情;
}
}
抛出新的UsernameNotFoundException(“用户”+s+“notfound”);
}
公共列表getUsers(){
返回用户;
}
}
maven文件中的一些内容

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

org.springframework.boot
spring启动程序父级
2.0.3.1发布
UTF-8
UTF-8
1.8
org.springframework.boot
弹簧启动安全
org.springframework.boot
SpringBootStarterWeb
org.springframework.boot
弹簧起动试验
测试
org.springframework.security.oauth
spring-security-oauth2
2.3.3.2发布
org.springframework.security.oauth.boot
spring-security-oauth2-autoconfigure
2.0.1.1发布
org.springframework.boot
spring引导配置处理器
真的

您解决了这个问题吗?。我也有同样的问题,我创建了一个新的应用程序,幸运的是它成功了。