Search in sources :

Example 1 with AuthzAuthenticationRequest

use of org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest in project uaa by cloudfoundry.

the class LoginAuthenticationManagerTests method testSuccessfulAuthenticationPublishesEvent.

@Test
void testSuccessfulAuthenticationPublishesEvent() {
    UaaUser user = UaaUserTestFactory.getUser("FOO", "foo", "fo@test.org", "Foo", "Bar");
    Mockito.when(userDatabase.retrieveUserByName("foo", OriginKeys.LOGIN_SERVER)).thenReturn(user);
    AuthzAuthenticationRequest authenticationRequest = UaaAuthenticationTestFactory.getAuthenticationRequest("foo");
    manager.authenticate(authenticationRequest);
    assertEquals(1, publisher.getEventCount());
    assertEquals("foo", publisher.getLatestEvent().getUser().getUsername());
}
Also used : UaaUserMatcher.aUaaUser(org.cloudfoundry.identity.uaa.user.UaaUserMatcher.aUaaUser) UaaUser(org.cloudfoundry.identity.uaa.user.UaaUser) AuthzAuthenticationRequest(org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest) Test(org.junit.jupiter.api.Test)

Example 2 with AuthzAuthenticationRequest

use of org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest in project uaa by cloudfoundry.

the class LoginInfoEndpoint method generateAutologinCode.

@RequestMapping(value = "/autologin", method = RequestMethod.POST)
@ResponseBody
public AutologinResponse generateAutologinCode(@RequestBody AutologinRequest request, @RequestHeader(value = "Authorization", required = false) String auth) throws Exception {
    if (mfaChecker.isMfaEnabled(IdentityZoneHolder.get())) {
        throw new BadCredentialsException("MFA is required");
    }
    if (auth == null || (!auth.startsWith("Basic"))) {
        throw new BadCredentialsException("No basic authorization client information in request");
    }
    String username = request.getUsername();
    if (username == null) {
        throw new BadCredentialsException("No username in request");
    }
    Authentication userAuthentication = null;
    if (authenticationManager != null) {
        String password = request.getPassword();
        if (!hasText(password)) {
            throw new BadCredentialsException("No password in request");
        }
        userAuthentication = authenticationManager.authenticate(new AuthzAuthenticationRequest(username, password, null));
    }
    String base64Credentials = auth.substring("Basic".length()).trim();
    String credentials = new String(getDecoder().decode(base64Credentials.getBytes()), UTF_8.name());
    // credentials = username:password
    final String[] values = credentials.split(":", 2);
    if (values == null || values.length == 0) {
        throw new BadCredentialsException("Invalid authorization header.");
    }
    String clientId = values[0];
    Map<String, String> codeData = new HashMap<>();
    codeData.put("client_id", clientId);
    codeData.put("username", username);
    if (userAuthentication != null && userAuthentication.getPrincipal() instanceof UaaPrincipal) {
        UaaPrincipal p = (UaaPrincipal) userAuthentication.getPrincipal();
        if (p != null) {
            codeData.put("user_id", p.getId());
            codeData.put(OriginKeys.ORIGIN, p.getOrigin());
        }
    }
    ExpiringCode expiringCode = expiringCodeStore.generateCode(JsonUtils.writeValueAsString(codeData), new Timestamp(System.currentTimeMillis() + 5 * 60 * 1000), ExpiringCodeType.AUTOLOGIN.name(), IdentityZoneHolder.get().getId());
    return new AutologinResponse(expiringCode.getCode());
}
Also used : UaaPrincipal(org.cloudfoundry.identity.uaa.authentication.UaaPrincipal) ExpiringCode(org.cloudfoundry.identity.uaa.codestore.ExpiringCode) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) Authentication(org.springframework.security.core.Authentication) AuthzAuthenticationRequest(org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Timestamp(java.sql.Timestamp) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with AuthzAuthenticationRequest

use of org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest in project uaa by cloudfoundry.

the class AutologinAuthenticationManagerTest method setUp.

@BeforeEach
void setUp() {
    IdentityZoneHolder.clear();
    IdentityZoneHolder.setProvisioning(null);
    clientId = new RandomValueStringGenerator().generate();
    manager = new AutologinAuthenticationManager();
    codeStore = mock(ExpiringCodeStore.class);
    userDatabase = mock(UaaUserDatabase.class);
    clientDetailsService = mock(MultitenantClientServices.class);
    manager.setExpiringCodeStore(codeStore);
    manager.setClientDetailsService(clientDetailsService);
    manager.setUserDatabase(userDatabase);
    Map<String, String> info = new HashMap<>();
    info.put("code", "the_secret_code");
    UaaAuthenticationDetails details = new UaaAuthenticationDetails(new MockHttpServletRequest(), clientId);
    authenticationToken = new AuthzAuthenticationRequest(info, details);
}
Also used : MultitenantClientServices(org.cloudfoundry.identity.uaa.zone.MultitenantClientServices) HashMap(java.util.HashMap) UaaAuthenticationDetails(org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails) AutologinAuthenticationManager(org.cloudfoundry.identity.uaa.authentication.manager.AutologinAuthenticationManager) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AuthzAuthenticationRequest(org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest) ExpiringCodeStore(org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStore) RandomValueStringGenerator(org.springframework.security.oauth2.common.util.RandomValueStringGenerator) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) UaaUserDatabase(org.cloudfoundry.identity.uaa.user.UaaUserDatabase) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 4 with AuthzAuthenticationRequest

use of org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest in project uaa by cloudfoundry.

the class AutologinAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof AuthzAuthenticationRequest)) {
        return null;
    }
    AuthzAuthenticationRequest request = (AuthzAuthenticationRequest) authentication;
    Map<String, String> info = request.getInfo();
    String code = info.get("code");
    ExpiringCode expiringCode = doRetrieveCode(code);
    Map<String, String> codeData = null;
    try {
        if (expiringCode == null) {
            logger.debug("Autologin code has expired");
            throw new InvalidCodeException("expired_code", "Expired code", 422);
        }
        codeData = JsonUtils.readValue(expiringCode.getData(), new TypeReference<Map<String, String>>() {
        });
        if (!isAutologinCode(expiringCode.getIntent(), codeData.get("action"))) {
            logger.debug("Code is not meant for autologin");
            throw new InvalidCodeException("invalid_code", "Not an autologin code", 422);
        }
    } catch (JsonUtils.JsonUtilException x) {
        throw new BadCredentialsException("JsonConversion error", x);
    }
    String userId = codeData.get("user_id");
    String clientId = codeData.get(OAuth2Utils.CLIENT_ID);
    if (clientId == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client id missing");
    }
    try {
        clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (NoSuchClientException x) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client is missing");
    }
    UaaUser user = null;
    try {
        user = userDatabase.retrieveUserById(userId);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("Cannot redeem provided code for user, user is missing");
    }
    UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
    if (!clientId.equals(details.getClientId())) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client mismatch");
    }
    UaaPrincipal principal = new UaaPrincipal(user);
    return new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, (UaaAuthenticationDetails) authentication.getDetails());
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UaaAuthenticationDetails(org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails) AuthzAuthenticationRequest(org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidCodeException(org.cloudfoundry.identity.uaa.authentication.InvalidCodeException) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) UaaPrincipal(org.cloudfoundry.identity.uaa.authentication.UaaPrincipal) ExpiringCode(org.cloudfoundry.identity.uaa.codestore.ExpiringCode) JsonUtils(org.cloudfoundry.identity.uaa.util.JsonUtils) UaaUser(org.cloudfoundry.identity.uaa.user.UaaUser) TypeReference(com.fasterxml.jackson.core.type.TypeReference) NoSuchClientException(org.springframework.security.oauth2.provider.NoSuchClientException)

Example 5 with AuthzAuthenticationRequest

use of org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest in project uaa by cloudfoundry.

the class LoginAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication request) throws AuthenticationException {
    if (!(request instanceof AuthzAuthenticationRequest)) {
        logger.debug("Cannot process request of type: " + request.getClass().getName());
        return null;
    }
    AuthzAuthenticationRequest req = (AuthzAuthenticationRequest) request;
    Map<String, String> info = req.getInfo();
    logger.debug("Processing authentication request for " + req.getName());
    SecurityContext context = SecurityContextHolder.getContext();
    if (context.getAuthentication() instanceof OAuth2Authentication) {
        OAuth2Authentication authentication = (OAuth2Authentication) context.getAuthentication();
        if (authentication.isClientOnly()) {
            UaaUser user = getUser(req, info);
            UaaAuthenticationDetails authdetails = (UaaAuthenticationDetails) req.getDetails();
            boolean addNewAccounts = authdetails != null && authdetails.isAddNew();
            try {
                if (NotANumber.equals(user.getId())) {
                    user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin());
                } else {
                    // we should never add new accounts if we specify user_id
                    addNewAccounts = false;
                    user = userDatabase.retrieveUserById(user.getId());
                }
            } catch (UsernameNotFoundException e) {
                // Not necessarily fatal
                if (addNewAccounts) {
                    // Register new users automatically
                    publish(new NewUserAuthenticatedEvent(user));
                    try {
                        user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin());
                    } catch (UsernameNotFoundException ex) {
                        throw new BadCredentialsException("Bad credentials");
                    }
                } else {
                    // if add_new=false then this is a bad user ID
                    throw new BadCredentialsException("Bad Credentials");
                }
            }
            Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), authdetails);
            publish(new IdentityProviderAuthenticationSuccessEvent(user, success, user.getOrigin(), identityZoneManager.getCurrentIdentityZoneId()));
            return success;
        }
    }
    logger.debug("Did not locate login credentials");
    return null;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UaaAuthenticationDetails(org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails) AuthzAuthenticationRequest(org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest) IdentityProviderAuthenticationSuccessEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) UaaPrincipal(org.cloudfoundry.identity.uaa.authentication.UaaPrincipal) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UaaAuthentication(org.cloudfoundry.identity.uaa.authentication.UaaAuthentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UaaUser(org.cloudfoundry.identity.uaa.user.UaaUser) SecurityContext(org.springframework.security.core.context.SecurityContext)

Aggregations

AuthzAuthenticationRequest (org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest)6 UaaAuthenticationDetails (org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails)4 HashMap (java.util.HashMap)3 UaaAuthentication (org.cloudfoundry.identity.uaa.authentication.UaaAuthentication)3 UaaPrincipal (org.cloudfoundry.identity.uaa.authentication.UaaPrincipal)3 UaaUser (org.cloudfoundry.identity.uaa.user.UaaUser)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 ExpiringCode (org.cloudfoundry.identity.uaa.codestore.ExpiringCode)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 Authentication (org.springframework.security.core.Authentication)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 Timestamp (java.sql.Timestamp)1 LinkedHashMap (java.util.LinkedHashMap)1 InvalidCodeException (org.cloudfoundry.identity.uaa.authentication.InvalidCodeException)1 IdentityProviderAuthenticationSuccessEvent (org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent)1 AutologinAuthenticationManager (org.cloudfoundry.identity.uaa.authentication.manager.AutologinAuthenticationManager)1 ExpiringCodeStore (org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStore)1 UaaUserDatabase (org.cloudfoundry.identity.uaa.user.UaaUserDatabase)1 UaaUserMatcher.aUaaUser (org.cloudfoundry.identity.uaa.user.UaaUserMatcher.aUaaUser)1