Search in sources :

Example 11 with UsernamePasswordAuthenticationToken

use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security by spring-projects.

the class UsernamePasswordAuthenticationTokenDeserializer method deserialize.

/**
	 * This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json.
	 * @param jp the JsonParser
	 * @param ctxt the DeserializationContext
	 * @return the user
	 * @throws IOException if a exception during IO occurs
	 * @throws JsonProcessingException if an error during JSON processing occurs
	 */
@Override
public UsernamePasswordAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    UsernamePasswordAuthenticationToken token = null;
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode jsonNode = mapper.readTree(jp);
    Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
    JsonNode principalNode = readJsonNode(jsonNode, "principal");
    Object principal = null;
    if (principalNode.isObject()) {
        principal = mapper.readValue(principalNode.toString(), new TypeReference<User>() {
        });
    } else {
        principal = principalNode.asText();
    }
    Object credentials = readJsonNode(jsonNode, "credentials").asText();
    List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").toString(), new TypeReference<List<GrantedAuthority>>() {
    });
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    } else {
        token = new UsernamePasswordAuthenticationToken(principal, credentials);
    }
    token.setDetails(readJsonNode(jsonNode, "details"));
    return token;
}
Also used : GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) JsonNode(com.fasterxml.jackson.databind.JsonNode) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with UsernamePasswordAuthenticationToken

use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security by spring-projects.

the class AbstractJaasAuthenticationProvider method authenticate.

/**
	 * Attempts to login the user given the Authentication objects principal and
	 * credential
	 *
	 * @param auth The Authentication object to be authenticated.
	 *
	 * @return The authenticated Authentication object, with it's grantedAuthorities set.
	 *
	 * @throws AuthenticationException This implementation does not handle 'locked' or
	 * 'disabled' accounts. This method only throws a AuthenticationServiceException, with
	 * the message of the LoginException that will be thrown, should the
	 * loginContext.login() method fail.
	 */
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
        return null;
    }
    UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
    Set<GrantedAuthority> authorities;
    try {
        // Create the LoginContext object, and pass our InternallCallbackHandler
        LoginContext loginContext = createLoginContext(new InternalCallbackHandler(auth));
        // Attempt to login the user, the LoginContext will call our
        // InternalCallbackHandler at this point.
        loginContext.login();
        // Create a set to hold the authorities, and add any that have already been
        // applied.
        authorities = new HashSet<GrantedAuthority>();
        // Get the subject principals and pass them to each of the AuthorityGranters
        Set<Principal> principals = loginContext.getSubject().getPrincipals();
        for (Principal principal : principals) {
            for (AuthorityGranter granter : this.authorityGranters) {
                Set<String> roles = granter.grant(principal);
                // return null.
                if ((roles != null) && !roles.isEmpty()) {
                    for (String role : roles) {
                        authorities.add(new JaasGrantedAuthority(role, principal));
                    }
                }
            }
        }
        // Convert the authorities set back to an array and apply it to the token.
        JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), request.getCredentials(), new ArrayList<GrantedAuthority>(authorities), loginContext);
        // Publish the success event
        publishSuccessEvent(result);
        // we're done, return the token.
        return result;
    } catch (LoginException loginException) {
        AuthenticationException ase = this.loginExceptionResolver.resolveException(loginException);
        publishFailureEvent(request, ase);
        throw ase;
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) LoginContext(javax.security.auth.login.LoginContext) LoginException(javax.security.auth.login.LoginException) Principal(java.security.Principal)

Example 13 with UsernamePasswordAuthenticationToken

use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security by spring-projects.

the class ClientApplication method main.

public static void main(String[] args) {
    String username = System.getProperty("username", "");
    String password = System.getProperty("password", "");
    String nrOfCallsString = System.getProperty("nrOfCalls", "");
    if ("".equals(username) || "".equals(password)) {
        System.out.println("You need to specify the user ID to use, the password to use, and optionally a number of calls " + "using the username, password, and nrOfCalls system properties respectively. eg for user rod, " + "use: -Dusername=rod -Dpassword=koala' for a single call per service and " + "use: -Dusername=rod -Dpassword=koala -DnrOfCalls=10 for ten calls per service.");
        System.exit(-1);
    } else {
        int nrOfCalls = 1;
        if (!"".equals(nrOfCallsString)) {
            nrOfCalls = Integer.parseInt(nrOfCallsString);
        }
        ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext("clientContext.xml");
        ClientApplication client = new ClientApplication(beanFactory);
        client.invokeContactManager(new UsernamePasswordAuthenticationToken(username, password), nrOfCalls);
        System.exit(0);
    }
}
Also used : FileSystemXmlApplicationContext(org.springframework.context.support.FileSystemXmlApplicationContext) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory)

Example 14 with UsernamePasswordAuthenticationToken

use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security by spring-projects.

the class WithUserDetailsSecurityContextFactory method createSecurityContext.

public SecurityContext createSecurityContext(WithUserDetails withUser) {
    String beanName = withUser.userDetailsServiceBeanName();
    UserDetailsService userDetailsService = StringUtils.hasLength(beanName) ? this.beans.getBean(beanName, UserDetailsService.class) : this.beans.getBean(UserDetailsService.class);
    String username = withUser.value();
    Assert.hasLength(username, "value() must be non empty String");
    UserDetails principal = userDetailsService.loadUserByUsername(username);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    return context;
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 15 with UsernamePasswordAuthenticationToken

use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security by spring-projects.

the class WithMockCustomUserSecurityContextFactory method createSecurityContext.

public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username());
    Authentication auth = new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
    context.setAuthentication(auth);
    return context;
}
Also used : Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Aggregations

UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)293 Test (org.junit.Test)149 Authentication (org.springframework.security.core.Authentication)110 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)33 GrantedAuthority (org.springframework.security.core.GrantedAuthority)33 UserDetails (org.springframework.security.core.userdetails.UserDetails)32 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)27 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)22 AuthenticationException (org.springframework.security.core.AuthenticationException)18 User (org.springframework.security.core.userdetails.User)16 SecurityContext (org.springframework.security.core.context.SecurityContext)15 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)15 OrcidProfileUserDetails (org.orcid.core.oauth.OrcidProfileUserDetails)13 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)11 ArrayList (java.util.ArrayList)10 Before (org.junit.Before)8 AccessDeniedException (org.springframework.security.access.AccessDeniedException)8