Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken.

Prototype

public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
        Collection<? extends GrantedAuthority> authorities) 

Source Link

Document

This constructor should only be used by AuthenticationManager or AuthenticationProvider implementations that are satisfied with producing a trusted (i.e.

Usage

From source file:io.github.azige.bbs.service.AccountService.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    Account account = accountRepository.findByAccountName(username);
    if (account == null) {
        throw new UsernameNotFoundException("User name not found");
    }/*from   w  w w.jav  a  2 s .  c  o m*/
    password = encryptPassword(password, account.getSalt());
    if (password.equals(account.getPassword())) {
        return new UsernamePasswordAuthenticationToken(account.getProfile(), password, Account.AUTHORITYS);
    }
    return authentication;
}

From source file:com.epam.reportportal.auth.integration.github.GitHubTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken)
        throws AuthenticationException, InvalidTokenException {
    GitHubClient gitHubClient = GitHubClient.withAccessToken(accessToken);
    UserResource gitHubUser = gitHubClient.getUser();

    List<String> allowedOrganizations = ofNullable(loginDetails.get().getRestrictions())
            .flatMap(restrictions -> ofNullable(restrictions.get("organizations")))
            .map(it -> Splitter.on(",").omitEmptyStrings().splitToList(it)).orElse(emptyList());
    if (!allowedOrganizations.isEmpty()) {
        boolean assignedToOrganization = gitHubClient.getUserOrganizations(gitHubUser).stream()
                .map(userOrg -> userOrg.login).anyMatch(allowedOrganizations::contains);
        if (!assignedToOrganization) {
            throw new InsufficientOrganizationException(
                    "User '" + gitHubUser.login + "' does not belong to allowed GitHUB organization");
        }//w ww .jav  a 2 s .  com
    }

    User user = replicator.replicateUser(gitHubUser, gitHubClient);

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getId(), "N/A",
            AuthUtils.AS_AUTHORITIES.apply(user.getRole()));

    Map<String, Serializable> extensionProperties = Collections.singletonMap("upstream_token", accessToken);
    OAuth2Request request = new OAuth2Request(null, loginDetails.get().getClientId(), null, true, null, null,
            null, null, extensionProperties);
    return new OAuth2Authentication(request, token);
}

From source file:sample.contact.DataSourcePopulator.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(mutableAclService, "mutableAclService required");
    Assert.notNull(template, "dataSource required");
    Assert.notNull(tt, "platformTransactionManager required");

    // Set a user account that will initially own all the created data
    Authentication authRequest = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
    SecurityContextHolder.getContext().setAuthentication(authRequest);

    try {//  www  .j a  v  a  2  s .c om
        template.execute("DELETE FROM CONTACTS");
        template.execute("DELETE FROM AUTHORITIES");
        template.execute("DELETE FROM USERS");
        template.execute("DELETE FROM ACL_ENTRY");
        template.execute("DELETE FROM ACL_OBJECT_IDENTITY");
        template.execute("DELETE FROM ACL_CLASS");
        template.execute("DELETE FROM ACL_SID");
    } catch (Exception e) {
        System.out.println("Failed to DELETE FROMs: " + e.getMessage());
    }
    /*
     * Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
     * password for rod is "koala" Encoded password for dianne is "emu" Encoded
     * password for scott is "wombat" Encoded password for peter is "opal" (but user
     * is disabled) Encoded password for bill is "wombat" Encoded password for bob is
     * "wombat" Encoded password for jane is "wombat"
     */
    template.execute(
            "INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);");
    template.execute(
            "INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_ADMIN');");
    template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_ADMIN');");

    template.execute("INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');");
    template.execute("INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');");
    template.execute("INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');");
    template.execute("INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');");
    template.execute("INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');");

    for (int i = 10; i < createEntities; i++) {
        String[] person = selectPerson();
        template.execute("INSERT INTO contacts VALUES (" + i + ", '" + person[2] + "', '"
                + person[0].toLowerCase() + "@" + person[1].toLowerCase() + ".com');");
    }

    // Create acl_object_identity rows (and also acl_class rows as needed
    for (int i = 1; i < createEntities; i++) {
        final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, new Long(i));
        tt.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus arg0) {
                mutableAclService.createAcl(objectIdentity);

                return null;
            }
        });
    }

    // Now grant some permissions
    grantPermissions(1, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(2, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.WRITE);
    grantPermissions(3, "rod", BasePermission.DELETE);
    grantPermissions(4, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(4, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(4, "scott", BasePermission.READ);
    grantPermissions(5, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(5, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.WRITE);
    grantPermissions(6, "dianne", BasePermission.DELETE);
    grantPermissions(6, "scott", BasePermission.READ);
    grantPermissions(7, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.READ);
    grantPermissions(8, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(9, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.WRITE);
    grantPermissions(9, "scott", BasePermission.DELETE);

    // Now expressly change the owner of the first ten contacts
    // We have to do this last, because "rod" owns all of them (doing it sooner would
    // prevent ACL updates)
    // Note that ownership has no impact on permissions - they're separate (ownership
    // only allows ACl editing)
    changeOwner(5, "dianne");
    changeOwner(6, "dianne");
    changeOwner(7, "scott");
    changeOwner(8, "dianne");
    changeOwner(9, "scott");

    String[] users = { "bill", "bob", "jane" }; // don't want to mess around with
    // consistent sample data
    Permission[] permissions = { BasePermission.ADMINISTRATION, BasePermission.READ, BasePermission.DELETE };

    for (int i = 10; i < createEntities; i++) {
        String user = users[rnd.nextInt(users.length)];
        Permission permission = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user, permission);

        String user2 = users[rnd.nextInt(users.length)];
        Permission permission2 = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user2, permission2);
    }

    SecurityContextHolder.clearContext();
}

From source file:com.amediamanager.controller.UserController.java

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String userPost(@ModelAttribute User user, BindingResult result, RedirectAttributes attr,
        HttpSession session) {/*from  www . ja  va2  s  .c  o m*/
    // Don't allow user name changes
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    user.setId(auth.getName());
    user.setEmail(auth.getName());

    // Update user and re-set val in session
    userService.update(user);

    // Update user auth object in security context
    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(auth.getName(), null,
            auth.getAuthorities());
    newAuth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(newAuth);

    return "redirect:/user";
}

From source file:org.shredzone.cilla.service.impl.UserServiceImpl.java

@Override
public void changePassword(User user, String oldPwd, String newPwd) throws CillaServiceException {
    if (user == null || oldPwd == null || newPwd == null) {
        throw new NullPointerException("null argument");
    }//from  w  w w .ja v a 2 s.c  o  m

    user.setPassword(newPwd);

    CillaUserDetails ud = new CillaUserDetails(user);
    UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user,
            user.getPassword(), ud.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(newAuthentication);
}

From source file:org.tibetjungle.demo.service.DataSourcePopulator.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(mutableAclService, "mutableAclService required");
    Assert.notNull(template, "dataSource required");
    Assert.notNull(tt, "platformTransactionManager required");

    // Set a user account that will initially own all the created data
    Authentication authRequest = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
    SecurityContextHolder.getContext().setAuthentication(authRequest);

    try {//from  w  ww. j  a va 2  s . c om
        template.execute("DROP TABLE CONTACTS");
        template.execute("DROP TABLE AUTHORITIES");
        template.execute("DROP TABLE USERS");
        template.execute("DROP TABLE ACL_ENTRY");
        template.execute("DROP TABLE ACL_OBJECT_IDENTITY");
        template.execute("DROP TABLE ACL_CLASS");
        template.execute("DROP TABLE ACL_SID");
    } catch (Exception e) {
        System.out.println("Failed to drop tables: " + e.getMessage());
    }

    template.execute("CREATE TABLE ACL_SID("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "PRINCIPAL BOOLEAN NOT NULL," + "SID VARCHAR_IGNORECASE(100) NOT NULL,"
            + "CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
    template.execute("CREATE TABLE ACL_CLASS("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "CLASS VARCHAR_IGNORECASE(100) NOT NULL," + "CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
    template.execute("CREATE TABLE ACL_OBJECT_IDENTITY("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "OBJECT_ID_CLASS BIGINT NOT NULL," + "OBJECT_ID_IDENTITY BIGINT NOT NULL,"
            + "PARENT_OBJECT BIGINT," + "OWNER_SID BIGINT," + "ENTRIES_INHERITING BOOLEAN NOT NULL,"
            + "CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),"
            + "CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),"
            + "CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),"
            + "CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
    template.execute("CREATE TABLE ACL_ENTRY("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,"
            + "MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,"
            + "AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),"
            + "CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),"
            + "CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");

    template.execute(
            "CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(60) NOT NULL,ENABLED BOOLEAN NOT NULL);");
    template.execute(
            "CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));");
    template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");

    template.execute(
            "CREATE TABLE CONTACTS(ID BIGINT NOT NULL PRIMARY KEY, CONTACT_NAME VARCHAR_IGNORECASE(50) NOT NULL, EMAIL VARCHAR_IGNORECASE(50) NOT NULL)");

    /*
       Passwords encoded using MD5, NOT in Base64 format, with null as salt
       Encoded password for rod is "koala"
       Encoded password for dianne is "emu"
       Encoded password for scott is "wombat"
       Encoded password for peter is "opal" (but user is disabled)
       Encoded password for bill is "wombat"
       Encoded password for bob is "wombat"
       Encoded password for jane is "wombat"
            
     */
    template.execute(
            "INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);");
    template.execute(
            "INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');");
    template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");

    template.execute("INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');");
    template.execute("INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');");
    template.execute("INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');");
    template.execute("INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');");
    template.execute("INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');");

    for (int i = 10; i < createEntities; i++) {
        String[] person = selectPerson();
        template.execute("INSERT INTO contacts VALUES (" + i + ", '" + person[2] + "', '"
                + person[0].toLowerCase() + "@" + person[1].toLowerCase() + ".com');");
    }

    // Create acl_object_identity rows (and also acl_class rows as needed
    for (int i = 1; i < createEntities; i++) {
        final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, new Long(i));
        tt.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus arg0) {
                mutableAclService.createAcl(objectIdentity);

                return null;
            }
        });
    }

    // Now grant some permissions
    grantPermissions(1, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(2, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.WRITE);
    grantPermissions(3, "rod", BasePermission.DELETE);
    grantPermissions(4, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(4, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(4, "scott", BasePermission.READ);
    grantPermissions(5, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(5, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.WRITE);
    grantPermissions(6, "dianne", BasePermission.DELETE);
    grantPermissions(6, "scott", BasePermission.READ);
    grantPermissions(7, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.READ);
    grantPermissions(8, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(9, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.WRITE);
    grantPermissions(9, "scott", BasePermission.DELETE);

    // Now expressly change the owner of the first ten contacts
    // We have to do this last, because "rod" owns all of them (doing it sooner would prevent ACL updates)
    // Note that ownership has no impact on permissions - they're separate (ownership only allows ACl editing)
    changeOwner(5, "dianne");
    changeOwner(6, "dianne");
    changeOwner(7, "scott");
    changeOwner(8, "dianne");
    changeOwner(9, "scott");

    String[] users = { "bill", "bob", "jane" }; // don't want to mess around with consistent sample data
    Permission[] permissions = { BasePermission.ADMINISTRATION, BasePermission.READ, BasePermission.DELETE };

    for (int i = 10; i < createEntities; i++) {
        String user = users[rnd.nextInt(users.length)];
        Permission permission = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user, permission);

        String user2 = users[rnd.nextInt(users.length)];
        Permission permission2 = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user2, permission2);
    }

    SecurityContextHolder.clearContext();
}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

private AuthenticationToken authenticateInternal(AbstractAuthenticationToken authenticationRequestToken) {
    boolean authenticated = false;
    String name = authenticationRequestToken.getName();
    String errorMessage = null;//w  w w  . ja v  a 2 s.  c om
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationRequestToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated && authentication.getDetails() == null) {
            // Try to load user details. Copy information into new token
            UsernamePasswordAuthenticationToken authenticationWithDetails = new UsernamePasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(),
                    authentication.getAuthorities());
            authenticationWithDetails.setDetails(userDao.getUserByUsername(authentication.getName()));
            authentication = authenticationWithDetails;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        name = authentication.getName();
    } catch (AuthenticationException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("User " + name + " failed to login. Reason: ", e);
        }
        authenticated = false;
        errorMessage = e.getMessage();
    }
    if (authenticated) {
        return new AuthenticationToken(name, new ArrayList<AuthenticationAttribute>());
    }
    return new AuthenticationToken(name, errorMessage);
}

From source file:ltistarter.lti.LTIOAuthAuthenticationHandler.java

@Override
public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication,
        OAuthAccessProviderToken authToken) {
    Collection<GrantedAuthority> authorities = new HashSet<>(authentication.getAuthorities());
    LTIRequest ltiRequest = (LTIRequest) request.getAttribute(LTIRequest.class.getName());
    if (ltiRequest == null) {
        throw new IllegalStateException("Cannot create authentication for LTI because the LTIRequest is null");
    }//from  ww  w  .ja  v a2  s.c  om

    // attempt to create a user Authority
    String username = ltiRequest.getLtiUserId();
    if (StringUtils.isBlank(username)) {
        username = authentication.getName();
    }

    // set appropriate permissions for this user based on LTI data
    if (ltiRequest.getUser() != null) {
        authorities.add(userGA);
    }
    if (ltiRequest.isRoleAdministrator()) {
        authorities.add(adminGA);
    }
    if (ltiRequest.isRoleInstructor()) {
        authorities.add(instructorGA);
    }
    if (ltiRequest.isRoleLearner()) {
        authorities.add(learnerGA);
    }

    // TODO store lti context and user id in the principal
    Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities,
            authentication.getConsumerCredentials().getConsumerKey(),
            authentication.getConsumerCredentials().getSignature(),
            authentication.getConsumerCredentials().getSignatureMethod(),
            authentication.getConsumerCredentials().getSignatureBaseString(),
            authentication.getConsumerCredentials().getToken());
    Authentication auth = new UsernamePasswordAuthenticationToken(principal, null, authorities);
    log.info("createAuthentication generated LTI auth principal (" + principal + "): req=" + request);
    return auth;
}

From source file:net.firejack.platform.web.security.spring.AuthenticationManager.java

private Authentication generateDefaultToken(IUserInfoProvider user, List<GrantedAuthority> authorities,
        HttpSession session) {// w w w  .j  av  a2s  . c om
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), authorities);
    token.setDetails(user);
    sessionManager.addUserToSession(user, session);
    return token;
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.SignupController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        return getCancelView();
    }//from ww w .jav  a 2 s  .c o  m

    if (log.isDebugEnabled()) {
        log.debug("entering 'onSubmit' method...");
    }
    Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
        this.getUserManager().saveUser(user);
    } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (UserExistsException e) {
        errors.rejectValue("username", "errors.existing.user",
                new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
        log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));

    try {
        sendUserMessage(user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (MailException me) {
        saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
}