jenkins.security.SecurityListener Java Examples

The following examples show how to use jenkins.security.SecurityListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
public HttpResponse doEscapeHatch(@QueryParameter("j_username") String username, @QueryParameter("j_password") String password) {
    randomWait(); // to slowdown brute forcing
    if(!isEscapeHatchEnabled()) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(this.escapeHatchUsername == null || this.escapeHatchSecret == null) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(escapeHatchUsername.equalsIgnoreCase(username) && escapeHatchSecret.getPlainText().equals(password)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
        if(isNotBlank(escapeHatchGroup)) {
            authorities.add(new GrantedAuthorityImpl(escapeHatchGroup));
        }
        String userName = "escape-hatch-admin";
        GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[authorities.size()]);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        		userName,
                "",
                grantedAuthorities
        );
        SecurityContextHolder.getContext().setAuthentication(token);
        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);
        return HttpRedirect.CONTEXT_ROOT;
    }
    return HttpResponses.redirectViaContextPath("loginError");
}
 
Example #2
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException {

        GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo);
        if(LOGGER.isLoggable(Level.FINEST)) {
		    StringBuilder grantedAuthoritiesAsString = new StringBuilder("(");
		    for(GrantedAuthority grantedAuthority : grantedAuthorities) {
		        grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
            }
            grantedAuthoritiesAsString.append(" )");
		    LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        User user = User.get(token.getName());
        // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object.
        user.addProperty(new OicUserProperty(userName, grantedAuthorities));

        if(emailFieldName!=null) {
	        String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName);
	        if (email != null) {
	            user.addProperty(new Mailer.UserProperty(email));
	        }
        }

        if(fullNameFieldName!=null) {
		    String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName);
		    if (fullName != null) {
		        user.setFullName(fullName);
		    }
        }

        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);

        return token;
    }
 
Example #3
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 4 votes vote down vote up
/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong.
 */
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
    String code = request.getParameter("code");

    if (StringUtils.isBlank(code)) {
        Log.info("doFinishLogin: missing code or private_token.");
        return HttpResponses.redirectToContextRoot();
    }

    String state = request.getParameter("state");

    HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token");
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("client_id", clientID));
    parameters.add(new BasicNameValuePair("client_secret", clientSecret));
    parameters.add(new BasicNameValuePair("code", code));
    parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request, state)));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost proxy = getProxy(httpPost);
    if (proxy != null) {
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        httpPost.setConfig(config);
    }

    org.apache.http.HttpResponse response = httpclient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.close();

    String accessToken = extractToken(content);

    if (StringUtils.isNotBlank(accessToken)) {
        // only set the access token if it exists.
        GitLabAuthenticationToken auth = new GitLabAuthenticationToken(accessToken, getGitlabApiUri(), TokenType.ACCESS_TOKEN);

        HttpSession session = request.getSession(false);
        if (session != null) {
            // avoid session fixation
            session.invalidate();
        }
        request.getSession(true);

        SecurityContextHolder.getContext().setAuthentication(auth);

        GitlabUser self = auth.getMyself();
        User user = User.current();
        if (user != null) {
            user.setFullName(self.getName());
            // Set email from gitlab only if empty
            if (!user.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
                user.addProperty(new Mailer.UserProperty(auth.getMyself().getEmail()));
            }
        }
        SecurityListener.fireAuthenticated(new GitLabOAuthUserDetails(self, auth.getAuthorities()));
    } else {
        Log.info("Gitlab did not return an access token.");
    }

    if (StringUtils.isNotBlank(state)) {
        return HttpResponses.redirectTo(state);
    }
    return HttpResponses.redirectToContextRoot();
}