Java org.springframework.security.crypto.codec.Base64 代码实例

・11 分钟阅读

以下是展示如何使用org.springframework.security.crypto.codec.Base64的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


private String getAuthorizationHeader(String clientId, String clientSecret) {
    String creds = String.format("%s:%s", clientId, clientSecret);
    try {
        return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Could not convert String");
    }
}
 

实例 2


@Test
public void testClientIdentityProviderWithoutAllowedProvidersForPasswordGrantWorksInOtherZone() throws Exception {
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    //a client without allowed providers in non default zone should always be rejected
    String subdomain = "testzone"+new RandomValueStringGenerator().generate();
    IdentityZone testZone = setupIdentityZone(subdomain);
    IdentityZoneHolder.set(testZone);
    IdentityProvider provider = setupIdentityProvider(Origin.UAA);
    String clientId2 = "testclient"+new RandomValueStringGenerator().generate();
    setUpClients(clientId2, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI, Arrays.asList(provider.getOriginKey()));
    String clientId = "testclient"+new RandomValueStringGenerator().generate();
    setUpClients(clientId, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI, null);
    String username = "testuser"+new RandomValueStringGenerator().generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, Origin.UAA, testZone.getId());
    getMockMvc().perform(post("/oauth/token")
        .with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"))
        .param("username", username)
        .param("password", "secret")
        .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
        .param(OAuth2Utils.RESPONSE_TYPE, "token")
        .param(OAuth2Utils.GRANT_TYPE, "password")
        .param(OAuth2Utils.CLIENT_ID, clientId))
        .andExpect(status().isOk());
    getMockMvc().perform(post("/oauth/token")
        .with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"))
        .param("username", username)
        .param("password", "secret")
        .header("Authorization", "Basic " + new String(Base64.encode((clientId2 + ":" + SECRET).getBytes())))
        .param(OAuth2Utils.RESPONSE_TYPE, "token")
        .param(OAuth2Utils.GRANT_TYPE, "password")
        .param(OAuth2Utils.CLIENT_ID, clientId2))
        .andExpect(status().isOk());
}
 

实例 3


@Test
public void testClientIdentityProviderRestrictionForPasswordGrant() throws Exception {
    //a client with allowed providers in the default zone should be rejected if the client is not allowed
    String clientId = "testclient"+new RandomValueStringGenerator().generate();
    String clientId2 = "testclient"+new RandomValueStringGenerator().generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    String idpOrigin = "origin-"+new RandomValueStringGenerator().generate();
    IdentityProvider provider = setupIdentityProvider(idpOrigin);
    setUpClients(clientId, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI, Arrays.asList(provider.getOriginKey()));
    setUpClients(clientId2, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI, null);
    //create a user in the UAA identity provider
    String username = "testuser"+new RandomValueStringGenerator().generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, Origin.UAA, IdentityZoneHolder.get().getId());
    getMockMvc().perform(post("/oauth/token")
        .param("username", username)
        .param("password", "secret")
        .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
        .param(OAuth2Utils.RESPONSE_TYPE, "token")
        .param(OAuth2Utils.GRANT_TYPE, "password")
        .param(OAuth2Utils.CLIENT_ID, clientId))
        .andExpect(status().isUnauthorized());
    getMockMvc().perform(post("/oauth/token")
        .param("username", username)
        .param("password", "secret")
        .header("Authorization", "Basic " + new String(Base64.encode((clientId2 + ":" + SECRET).getBytes())))
        .param(OAuth2Utils.RESPONSE_TYPE, "token")
        .param(OAuth2Utils.GRANT_TYPE, "password")
        .param(OAuth2Utils.CLIENT_ID, clientId2))
        .andExpect(status().isOk());
}
 

实例 4


/**
 * This function is called after the user successfully logs in.
 * Adds an attribute to the session to keep track of the currently logged-in user.
 * TODO: When the site is update, all sessions are lost, so everybody is logged out. Maybe do something smarter (maybe with cookies?) so this doesn't happen?
 */
@Override
@Transactional
public void onAuthenticationSuccess(HttpServletRequest request,
                HttpServletResponse response, Authentication authentication)
                                throws ServletException, IOException {
        //sessions never expire
        request.getSession().setMaxInactiveInterval(-1);
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String loggedInUser = user.getUsername();
        request.getSession().setAttribute(AttributeNames.isLoggedIn, true);
        request.getSession().setAttribute(AttributeNames.loggedInUser, loggedInUser);
        //redirect to the last page visited
        //TODO: this acts weird if the user opens multiple tabs or hits the back button before logging in
        String url = "/";
        Object urlObj = request.getSession().getAttribute("loginUrl");
        if(urlObj != null){
                url = (String) request.getSession().getAttribute(AttributeNames.lastPageVisited);
        }
        if(request.getSession().getAttribute("sso") != null){
                //https://meta.discourse.org/t/sso-example-for-jsp/22786
                String discourseSsoSecret = env.getProperty("discourse.sso.secret");
                String sso = (String) request.getSession().getAttribute("sso");
                String sig = (String) request.getSession().getAttribute("sig");
                //now remove them
                request.getSession().removeAttribute("sso");
                request.getSession().removeAttribute("sig");
                try {
                        if (checksum(discourseSsoSecret, sso).equals(sig)) {
                                Member member = memberDao.getMember(loggedInUser);
                            String urlDecode = URLDecoder.decode(sso, "UTF-8");
                            String nonce = new String(Base64.decode(urlDecode.getBytes("UTF-8")));
                            String urlEncode = nonce
                                    + "&name=" + URLEncoder.encode(member.getMemberName(), "UTF-8")
                                    + "&username=" + URLEncoder.encode(member.getMemberName(), "UTF-8")
                                    + "&email=" + URLEncoder.encode(member.getEmail(), "UTF-8")
                                    + "&external_id=" + URLEncoder.encode(member.getMemberName(), "UTF-8");
                            if(member.getImageUrl() != null && !member.getImageUrl().contains(" ")){
                                String s3Endpoint = env.getProperty("s3.endpoint");
                                urlEncode += "&avatar_url=" + URLEncoder.encode(s3Endpoint + "/users/" + member.getMemberName() + "/" + member.getImageUrl(), "UTF-8");
                                urlEncode += "&avatar_force_update=1";
                            }
                            String urlBase64 = new String(Base64.encode(urlEncode.getBytes("UTF-8")));
                            int length = 0;
                            int maxLength = urlBase64.length();
                            final int STEP = 60;
                            String urlBase64Encode = "";
                            while (length < maxLength) {
                                urlBase64Encode += urlBase64.substring(length, length + STEP < maxLength ? length + STEP : maxLength) + "n";
                                length += STEP;
                            }
                            response.sendRedirect("http://forum.staticvoidgames.com/session/sso_login?sso=" + URLEncoder.encode(urlBase64Encode, "UTF-8") + "&sig=" + checksum(discourseSsoSecret, urlBase64Encode));
                        }
                } 
                catch (InvalidKeyException | NoSuchAlgorithmException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        else{
                this.getRedirectStrategy().sendRedirect(request, response, url);
        }
}
 
讨论
淘淘あ西西 profile image