Search in sources :

Example 16 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ORCID-Source by ORCID.

the class SocialAjaxAuthenticationSuccessHandler method linkSocialAccount.

public void linkSocialAccount(HttpServletRequest request, HttpServletResponse response) {
    SocialType connectionType = socialContext.isSignedIn(request, response);
    if (connectionType != null) {
        Map<String, String> userMap = retrieveUserDetails(connectionType);
        String providerId = connectionType.value();
        UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
        if (userConnectionEntity != null) {
            if (!userConnectionEntity.isLinked()) {
                userConnectionEntity.setLinked(true);
                userConnectionEntity.setEmail(userMap.get("email"));
                userConnectionEntity.setOrcid(getRealUserOrcid());
                userConnectionManager.update(userConnectionEntity);
            }
        } else {
            throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
        }
    } else {
        throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SocialType(org.orcid.frontend.spring.web.social.config.SocialType) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity)

Example 17 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ORCID-Source by ORCID.

the class SocialController method post2FAVerificationCode.

@RequestMapping(value = { "/2FA/submitCode.json" }, method = RequestMethod.POST)
@ResponseBody
public TwoFactorAuthenticationCodes post2FAVerificationCode(@RequestBody TwoFactorAuthenticationCodes codes, HttpServletRequest request, HttpServletResponse response) {
    SocialType connectionType = socialContext.isSignedIn(request, response);
    if (connectionType != null) {
        Map<String, String> userMap = retrieveUserDetails(connectionType);
        String providerId = connectionType.value();
        String userId = socialContext.getUserId();
        UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
        if (userConnectionEntity != null) {
            if (userConnectionEntity.isLinked()) {
                validate2FACodes(userConnectionEntity.getOrcid(), codes);
                if (!codes.getErrors().isEmpty()) {
                    return codes;
                }
                UserconnectionPK pk = new UserconnectionPK(userId, providerId, userMap.get("providerUserId"));
                String aCredentials = new StringBuffer(providerId).append(":").append(userMap.get("providerUserId")).toString();
                PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), aCredentials);
                token.setDetails(getOrcidProfileUserDetails(userConnectionEntity.getOrcid()));
                Authentication authentication = authenticationManager.authenticate(token);
                userConnectionManager.updateLoginInformation(pk);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                codes.setRedirectUrl(calculateRedirectUrl(request, response));
            } else {
                codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/social/access");
            }
        } else {
            throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
        }
    } else {
        throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
    }
    return codes;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Authentication(org.springframework.security.core.Authentication) SocialType(org.orcid.frontend.spring.web.social.config.SocialType) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) UserconnectionPK(org.orcid.persistence.jpa.entities.UserconnectionPK) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 18 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project portal by ixinportal.

the class ItrusPortalUserDetailsService method loadUserByUsername.

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 资源编号集合
    Collection<Integer> resNums = new HashSet<Integer>();
    // 查询用户信息
    AdminExample adminex = new AdminExample();
    adminex.or().andAccountEqualTo(username.toLowerCase());
    Admin admin = sqlSession.selectOne("com.itrus.portal.db.AdminMapper.selectByExample", adminex);
    boolean isNonLocked = true;
    // 用户授权信息
    Collection authorities = new ArrayList();
    // 用户不存在,异常处理
    if (admin == null) {
        Integer count = sqlSession.selectOne("com.itrus.portal.db.AdminMapper.countByExample", null);
        if (count > 0)
            throw new UsernameNotFoundException(username);
        admin = new Admin();
        admin.setPassword("itrusyes");
        admin.setStatus("valid");
        admin.setCreateTime(new Date());
        InitSystemData license = InitSystemData.getDefault();
        resNums = license.getResNums();
        for (String title : license.getRoleTitle()) authorities.add(new SimpleGrantedAuthority(title));
    } else {
        // 项目管理员
        AdminRoleExample roleex = new AdminRoleExample();
        roleex.or().andIdEqualTo(admin.getAdminRole());
        AdminRole adminRole = sqlSession.selectOne("com.itrus.portal.db.AdminRoleMapper.selectByExample", roleex);
        RoleAndResourcesExample rarEx = new RoleAndResourcesExample();
        rarEx.or().andAdminRoleEqualTo(adminRole.getId());
        List<RoleAndResources> roleAndRes = sqlSession.selectList("com.itrus.portal.db.RoleAndResourcesMapper.selectByExample", rarEx);
        for (RoleAndResources rar : roleAndRes) {
            SysResources res = cacheCustomer.getResById(rar.getSysResources());
            resNums.add(res.getResNum());
            // 不能为null角色名称
            if (res.getResRoleName() != null) {
                authorities.add(new SimpleGrantedAuthority(res.getResRoleName()));
            }
        }
    }
    String pass = admin.getPassword();
    if (pass != null && pass.length() != 40)
        // pass = PassUtil.doDigestSHA1(pass,username);
        pass = passwordEncoder.encodePassword(pass, username);
    isNonLocked = "valid".equalsIgnoreCase(admin.getStatus()) ? true : false;
    return new PortalUser(admin.getId(), username, pass, isNonLocked, admin.getProjects(), admin.getProject(), admin.getCreateTime(), resNums, authorities);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ArrayList(java.util.ArrayList) AdminRoleExample(com.itrus.portal.db.AdminRoleExample) RoleAndResources(com.itrus.portal.db.RoleAndResources) Admin(com.itrus.portal.db.Admin) InitSystemData(com.itrus.portal.utils.InitSystemData) Date(java.util.Date) PortalUser(com.itrus.portal.utils.PortalUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SysResources(com.itrus.portal.db.SysResources) Collection(java.util.Collection) AdminRole(com.itrus.portal.db.AdminRole) AdminExample(com.itrus.portal.db.AdminExample) RoleAndResourcesExample(com.itrus.portal.db.RoleAndResourcesExample) HashSet(java.util.HashSet)

Example 19 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project CILManagement-Server by LiuinStein.

the class MyAuthenticationFailureHandle method onAuthenticationFailure.

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    RestfulResult result = new RestfulResult(1, e.getMessage(), new HashMap<>());
    SecurityRestfulResponsePrinter responseHandle = new SecurityRestfulResponsePrinter();
    responseHandle.print(request, response, result);
    if (e instanceof UsernameNotFoundException) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) RestfulResult(cn.opencil.vo.RestfulResult)

Example 20 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project CILManagement-Server by LiuinStein.

the class MyAuthenticationFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if ("application/json".equals(request.getHeader("Content-Type"))) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuilder.toString());
            this.userId = jsonObject.getLong("username");
            this.password = jsonObject.getString("password");
        } catch (Exception e) {
            throw new UsernameNotFoundException("username error");
        }
    }
    return super.attemptAuthentication(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) JSONObject(com.alibaba.fastjson.JSONObject) BufferedReader(java.io.BufferedReader) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Aggregations

UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)132 GrantedAuthority (org.springframework.security.core.GrantedAuthority)40 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 UserDetails (org.springframework.security.core.userdetails.UserDetails)36 Authentication (org.springframework.security.core.Authentication)24 Transactional (org.springframework.transaction.annotation.Transactional)20 Logger (org.slf4j.Logger)18 LoggerFactory (org.slf4j.LoggerFactory)18 java.util (java.util)16 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)15 Collectors (java.util.stream.Collectors)14 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)14 Component (org.springframework.stereotype.Component)14 User (org.springframework.security.core.userdetails.User)13 ArrayList (java.util.ArrayList)12 HashSet (java.util.HashSet)11 UserRepository (io.github.jhipster.sample.repository.UserRepository)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 User (io.github.jhipster.sample.domain.User)6 Date (java.util.Date)6