Spring cannot configure authorization server

I created a simple authorization server, but I can’t configure it.

  • Launch both applications (8080 for the auth server and 9999 for the client).
  • Go to localhost:9999/clientand redirect to localhost:8080/login(as expected).
  • Fill in the registration form with user / user.
  • Get redirected to localhost:9999/client(as expected), but Hello, nullinstead Hello, user.

However, if you go straight to localhost:8080/me, I have {"name":"user"}. How can i get it Hello, user?

Authorization server

@RestController
@EnableAuthorizationServer
@SpringBootApplication
public class Application extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping({ "/user", "/me" })
    public Map<String, String> user(Principal principal) {
        return Collections.singletonMap("name", principal == null ? "null" : principal.getName());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("user").authorities(AuthorityUtils.NO_AUTHORITIES);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();
    }
}

Application properties

security:
  oauth2:
    client:
      client-id: clientid
      client-secret: clientsecret
      scope: read,write
      auto-approve-scopes: '.*'

Client

@Configuration
@EnableAutoConfiguration
@EnableOAuth2Sso
@RestController
public class Client {

    @GetMapping("/")
    public String home(Principal principal) {
        return "Hello, " + principal.getName();
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Client.class)
                .properties("spring.config.name=client").run(args);
    }

}

Client Properties

server:
  port: 9999
  context-path: /client
security:
  oauth2:
    client:
      client-id: clientid
      client-secret: clientsecret
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      user-info-uri: http://localhost:8080/me

UPDATE:
, , ssoFilter, OAuth2. loginForm.
example GitHub. , .

+4
4

9999 8080. HTTP- cross-origin, , , , .

HTTP (CORS)

spring - RESTful

CORS , .

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*"); //for production add only origins which should be allowed to access now for demo purposes this accepts all.
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); //i would reduce this method list if not all methods used this is added just for demo purposes
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

spring, , .

"web.xml" :

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.mycompany.CorsFilter</filter-class>
</filter>

A

<filter-mapping>
        <filter-name>CORS</filter-name>
        <servlet-name>MyServlet</servlet-name>
</filter-mapping>

B :

<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern> <!--this will add cors on all apps-->
</filter-mapping>
+1

org.springframework.cloud.security.oauth2.resource.UserInfoTokenServices, , , /me.

, , , , , , ROLE_USER, , OAuth2Authentication .

0

, .

@EnableOAuth2Client
@RestController
@EnableAuthorizationServer
@SpringBootApplication
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class Application extends WebSecurityConfigurerAdapter {

@Autowired
OAuth2ClientContext oauth2ClientContext;


public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@GetMapping({"/user", "/me"})
public Map<String, String> user(Principal principal) {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    return Collections.singletonMap("name", principal == null ? "null" : principal.getName());
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("user").password("user").authorities(AuthorityUtils.NO_AUTHORITIES);
}

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
        // @formatter:on
    }
}

@Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(filter);
    registration.setOrder(-100);
    return registration;
}

private Filter authFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
            path);
    OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(
            client.getResource().getUserInfoUri(), client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
    }
}

class ClientResources {

@NestedConfigurationProperty
private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

@NestedConfigurationProperty
private ResourceServerProperties resource = new ResourceServerProperties();

public AuthorizationCodeResourceDetails getClient() {
    return client;
}

public ResourceServerProperties getResource() {
    return resource;
    }
}

TokenFilter ssoFilter.

0

auth (localhost), -, , , http http cookie.

Try specifying it as 127.0.0.1, and the other as localhost, so that your browser associates HTTP cookies with their correct endpoints.

-1
source

Source: https://habr.com/ru/post/1672606/


All Articles