Example usage for org.springframework.security.core Authentication getName

List of usage examples for org.springframework.security.core Authentication getName

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getName.

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:com.alehuo.wepas2016projekti.controller.AdminController.java

/**
 * Kuvan poistaminen sen ID:n perusteella
 *
 * @param a Autentikointi//from   w w  w. j  a v  a  2  s  .c o  m
 * @param photoId Kuvan id
 * @return Nkym
 */
@Transactional
@RequestMapping(value = "/image", method = RequestMethod.POST)
public String deletePhoto(Authentication a, @RequestParam Long photoId) {
    Image i = imageRepo.findOne(photoId);
    //Aseta pois nkyvilt
    i.setVisible(false);
    //Tallenna
    imageRepo.save(i);
    //Logita
    LOG.log(Level.INFO, "Paakayttaja ''{0}'' poisti kuvan ''{1}''", new Object[] { a.getName(), i.getUuid() });
    return "redirect:/";
}

From source file:org.sharetask.security.WorkspaceOwnerPermission.java

@Override
public boolean isAllowed(final Authentication authentication, final Object targetDomainObject) {
    boolean result;
    Assert.isTrue(isAuthenticated(authentication), "UserAuthentication is not authenticated!");
    Assert.isTrue(targetDomainObject instanceof Long);
    final Long workspaceId = (Long) targetDomainObject;
    final String userName = authentication.getName();
    final Workspace workspace = this.workspaceRepository.read(workspaceId);
    if (isWorkspaceOwner(workspace, userName)) {
        result = true;//from w  w w.ja  va  2s .  com
    } else {
        result = false;
    }
    return result;
}

From source file:org.unidle.config.SocialConfiguration.java

@Bean
@Scope(value = "request", proxyMode = INTERFACES)
public ConnectionRepository connectionRepository() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
    }/*from   w  w  w  .j  a  v a  2  s.com*/

    final String uuid = authentication.getName();

    return usersConnectionRepository.createConnectionRepository(uuid);
}

From source file:de.blizzy.documentr.web.access.UserController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@PreAuthorize("hasApplicationPermission(ADMIN)")
public String saveUser(@ModelAttribute @Valid UserForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException {

    User user = userStore.getUser(authentication.getName());

    if (StringUtils.isNotBlank(form.getOriginalLoginName())
            && !form.getOriginalLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME)
            && StringUtils.equals(form.getLoginName(), UserStore.ANONYMOUS_USER_LOGIN_NAME)) {

        bindingResult.rejectValue("loginName", "user.loginName.invalid"); //$NON-NLS-1$ //$NON-NLS-2$
        return "/user/edit"; //$NON-NLS-1$
    }//from w ww. j ava  2s.  c  om

    if (!form.getLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME)) {
        if (StringUtils.isNotBlank(form.getLoginName()) && (StringUtils.isBlank(form.getOriginalLoginName())
                || !form.getLoginName().equals(form.getOriginalLoginName()))) {

            try {
                if (userStore.getUser(form.getLoginName()) != null) {
                    bindingResult.rejectValue("loginName", "user.loginName.exists"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (UserNotFoundException e) {
                // okay
            }
        }

        if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword1())) {

            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword2())) {

            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2())) {
            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isBlank(form.getPassword2())) {
            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2())
                && !StringUtils.equals(form.getPassword1(), form.getPassword2())) {

            bindingResult.rejectValue("password1", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$
            bindingResult.rejectValue("password2", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (bindingResult.hasErrors()) {
            return "/user/edit"; //$NON-NLS-1$
        }

        User existingUser = null;
        String password = null;
        if (StringUtils.isNotBlank(form.getOriginalLoginName())) {
            try {
                existingUser = userStore.getUser(form.getOriginalLoginName());
                password = existingUser.getPassword();
            } catch (UserNotFoundException e) {
                // okay
            }
        }

        if (StringUtils.isNotBlank(form.getPassword1())) {
            password = passwordEncoder.encodePassword(form.getPassword1(), form.getLoginName());
        }

        if (StringUtils.isBlank(password)) {
            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (bindingResult.hasErrors()) {
            return "/user/edit"; //$NON-NLS-1$
        }

        String newUserName = form.getOriginalLoginName();
        if (StringUtils.isBlank(newUserName)) {
            newUserName = form.getLoginName();
        }

        User newUser = new User(newUserName, password, form.getEmail(), form.isDisabled());
        if (existingUser != null) {
            for (OpenId openId : existingUser.getOpenIds()) {
                newUser.addOpenId(openId);
            }
        }
        userStore.saveUser(newUser, user);

        if (StringUtils.isNotBlank(form.getOriginalLoginName())
                && !StringUtils.equals(form.getLoginName(), form.getOriginalLoginName())) {

            userStore.renameUser(form.getOriginalLoginName(), form.getLoginName(), user);
        }
    }

    String[] authorityStrs = StringUtils.defaultString(form.getAuthorities()).split("\\|"); //$NON-NLS-1$
    Set<RoleGrantedAuthority> authorities = Sets.newHashSet();
    for (String authorityStr : authorityStrs) {
        if (StringUtils.isNotBlank(authorityStr)) {
            String[] parts = authorityStr.split(":"); //$NON-NLS-1$
            Assert.isTrue(parts.length == 3);
            Type type = Type.valueOf(parts[0]);
            String targetId = parts[1];
            String roleName = parts[2];
            authorities.add(new RoleGrantedAuthority(new GrantedAuthorityTarget(targetId, type), roleName));
        }
    }
    userStore.saveUserAuthorities(form.getLoginName(), authorities, user);

    return "redirect:/users"; //$NON-NLS-1$
}

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

@Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    // This must be re-parsed here because SECOAUTH forces us to call things in a strange order
    if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))
            && authorizationRequest.getExtensions().get(CSRF) != null && authorizationRequest.getExtensions()
                    .get(CSRF).equals(authorizationRequest.getApprovalParameters().get(CSRF))) {

        authorizationRequest.setApproved(true);

        // process scopes from user input
        Set<String> allowedScopes = Sets.newHashSet();
        Map<String, String> approvalParams = authorizationRequest.getApprovalParameters();

        Set<String> keys = approvalParams.keySet();

        for (String key : keys) {
            if (key.startsWith("scope_")) {
                //This is a scope parameter from the approval page. The value sent back should
                //be the scope string. Check to make sure it is contained in the client's
                //registered allowed scopes.

                String scope = approvalParams.get(key);
                Set<String> approveSet = Sets.newHashSet(scope);

                //Make sure this scope is allowed for the given client
                if (systemScopes.scopesMatch(client.getScope(), approveSet)) {

                    // If it's structured, assign the user-specified parameter
                    SystemScope systemScope = systemScopes.getByValue(scope);
                    if (systemScope != null && systemScope.isStructured()) {
                        String paramValue = approvalParams.get("scopeparam_" + scope);
                        if (!Strings.isNullOrEmpty(paramValue)) {
                            allowedScopes.add(scope + ":" + paramValue);
                        } else {
                            allowedScopes.add(scope);
                        }/*from   ww  w  .j a  va 2 s  .  c  om*/
                        // .. and if it's unstructured, we're all set
                    } else {
                        allowedScopes.add(scope);
                    }
                }

            }
        }

        // inject the user-allowed scopes into the auth request
        authorizationRequest.setScope(allowedScopes);

        //Only store an ApprovedSite if the user has checked "remember this decision":
        String remember = authorizationRequest.getApprovalParameters().get("remember");
        if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) {

            Date timeout = null;
            if (remember.equals("one-hour")) {
                // set the timeout to one hour from now
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.HOUR, 1);
                timeout = cal.getTime();
            }

            ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout,
                    allowedScopes);
            String newSiteId = newSite.getId().toString();
            authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId);
        }

        setAuthTime(authorizationRequest);

    }

    return authorizationRequest;
}

From source file:com.auditbucket.helper.SecurityHelper.java

public String getUserName(boolean exceptionOnNull, boolean isSysUser) {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    if (a == null)
        if (exceptionOnNull)
            throw new SecurityException("User is not authenticated");
        else//  ww w . jav a 2 s  .  co  m
            return null;

    if (isSysUser) {
        SystemUser su = getSysUser(a.getName());
        if (su == null)
            throw new IllegalArgumentException("Not authorised");
    }
    return a.getName();
}

From source file:cherry.sqlman.tool.load.SqlLoadControllerImpl.java

@Override
public ModelAndView create(SqlLoadForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }/*from w  w  w.  j  av a  2 s.c  om*/

    int id = loadService.create(form, auth.getName());
    form.setFile(null);

    return redirect(redirectOnInit(redirectOnCreate(id).toUriString(), null)).build();
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Check logged in user./*from  w  w w  .j  a v a  2s  .c  o m*/
 * @param email {@link String}
 * @return boolean
 */
public boolean isUser(final String email) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    return auth != null && email.equals(auth.getName());
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code,
        String redirectUri, String grantType, String refreshToken, String state) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();

    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }/*from  w  w w .j a  v a2s . c  o  m*/

    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao
                .find(code);

        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }

            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE)
                    || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(authorizationParameters);

    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);

    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object params[] = { grantType };
    if (token == null) {
        LOGGER.info(
                "Unsupported grant type for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(
                localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info(
            "OAuth2 access token granted: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}, token={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri, token });

    return token;
}

From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDAuthenticationProviderTest.java

/**
 * Tests authenticating a user via CrowmdmapID
 *//* www. j  ava 2s.c o m*/
@SuppressWarnings("unchecked")
@Test
public void authenticate() {
    Authentication mockAuthentication = mock(Authentication.class);
    Object mockCredentials = mock(Object.class);
    User mockUser = mock(User.class);

    Set<Role> userRoles = new HashSet<Role>();
    Role role = new Role();
    role.setName("user");
    userRoles.add(role);

    when(mockAuthentication.getName()).thenReturn("test@swiftapp.com");
    when(mockAuthentication.getCredentials()).thenReturn(mockCredentials);
    when(mockCredentials.toString()).thenReturn("pa55w0rd");
    when(mockCrowdmapIDClient.signIn(anyString(), anyString())).thenReturn(true);
    when(mockUserDao.findByUsernameOrEmail(anyString())).thenReturn(mockUser);
    when(mockUser.getRoles()).thenReturn(userRoles);

    Authentication authentication = authenticationProvider.authenticate(mockAuthentication);
    List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities();

    verify(mockUserDao).findByUsernameOrEmail("test@swiftapp.com");
    verify(mockCrowdmapIDClient).signIn("test@swiftapp.com", "pa55w0rd");
    assertEquals(1, authorities.size());
    assertEquals("ROLE_USER", authorities.get(0).getAuthority());
}