org.pac4j.core.profile.CommonProfile Java Examples

The following examples show how to use org.pac4j.core.profile.CommonProfile. 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: SecurityContext.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the authentication and authorization of NNA.
 *
 * @param appConf the security configuration
 * @param jwtAuth the JWT authentication object
 * @param jwtGen the JWT generator object
 * @param ldapAuthenticator ldap authenticator
 */
public void init(
    ApplicationConfiguration appConf,
    JwtAuthenticator jwtAuth,
    JwtGenerator<CommonProfile> jwtGen,
    LdapAuthenticator ldapAuthenticator) {
  this.applicationConfiguration = appConf;
  this.jwtAuthenticator = jwtAuth;
  this.jwtGenerator = jwtGen;
  this.ldapAuthenticator = ldapAuthenticator;

  this.adminUsers = new UserSet(appConf.getAdminUsers());
  this.writeUsers = new UserSet(appConf.getWriteUsers());
  this.readOnlyUsers = new UserSet(appConf.getReadOnlyUsers());
  this.cacheReaderUsers = new UserSet(appConf.getCacheReaderUsers());
  this.localOnlyUsers = new UserPasswordSet(appConf.getLocalOnlyUsers());

  this.init = true;
}
 
Example #2
Source File: SecurityContext.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
private boolean localLogin(
    HttpServletRequest request, HttpServletResponse response, String username, String password)
    throws AuthenticationException {
  if (localOnlyUsers.allows(username)) {
    if (localOnlyUsers.authenticate(username, password)) {
      LOG.debug("Login success via [LOCAL] for: {} at {}", username, request.getRemoteAddr());
      CommonProfile profile = new CommonProfile();
      profile.setId(username);
      String generate = jwtGenerator.generate(profile);
      response.addHeader("Set-Cookie", "nna-jwt-token=" + generate);
      currentUser.set(username);
      return true;
    } else {
      LOG.info("Login failed via [LOCAL] for: {}", request.getRemoteAddr());
      throw new BadCredentialsException("Invalid credentials for: " + username);
    }
  }
  return false;
}
 
Example #3
Source File: Pac4jUser.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
    int posLocal = super.readFromBuffer(pos, buffer);
    final int jsonByteCount = buffer.getInt(posLocal);
    posLocal += 4;
    final byte[] jsonBytes = buffer.getBytes(posLocal, posLocal + jsonByteCount);
    posLocal += jsonByteCount;

    final String json = new String(jsonBytes, StandardCharsets.UTF_8);
    final JsonObject profiles = new JsonObject(json);

    final Map<String, CommonProfile> decodedUserProfiles = profiles.stream()
            .filter(e -> e.getValue() instanceof JsonObject)
            .map(e -> new MappedPair<>(e.getKey(),
                    (CommonProfile) DefaultJsonConverter.getInstance().decodeObject(e.getValue())))
            .collect(toMap(e -> e.key, e -> e.value));

    setUserProfiles(decodedUserProfiles);
    return posLocal;
}
 
Example #4
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Function<ContainerRequest, ?> createValueProvider(Parameter parameter) {
    if (parameter.isAnnotationPresent(Pac4JProfileManager.class)) {
        if (ProfileManager.class.isAssignableFrom(parameter.getRawType())) {
            return manager.get();
        }

        throw new IllegalStateException("Cannot inject a Pac4J profile manager into a parameter of type "
            + parameter.getRawType().getName());
    }

    if (parameter.isAnnotationPresent(Pac4JProfile.class)) {
        if (CommonProfile.class.isAssignableFrom(parameter.getRawType())) {
            return profile.get();
        }

        if (Optional.class.isAssignableFrom(parameter.getRawType())) {
            List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(parameter.getRawType());
            ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null;
            if (ctp == null || CommonProfile.class.isAssignableFrom(ctp.rawClass())) {
                return optProfile.get();
            }
        }

        throw new IllegalStateException(
            "Cannot inject a Pac4J profile into a parameter of type " + parameter.getRawType().getName());
    }

    return null;
}
 
Example #5
Source File: SecurityContext.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
private boolean ldapLogin(
    HttpServletRequest request, HttpServletResponse response, String username, String password)
    throws HttpAction {
  if (ldapAuthenticator != null) {
    RuntimeException authFailedEx = null;
    Set<String> ldapBaseDns = applicationConfiguration.getLdapBaseDn();
    for (String ldapBaseDn : ldapBaseDns) {
      String ldapDnRegexd = ldapBaseDn.replaceAll("%u", username);
      ldapAuthenticator.getLdapAuthenticator().setDnResolver(new FormatDnResolver(ldapDnRegexd));
      UsernamePasswordCredentials credentials =
          new UsernamePasswordCredentials(username, password, request.getRemoteAddr());
      try {
        ldapAuthenticator.validate(credentials, new J2EContext(request, response));
      } catch (RuntimeException e) {
        authFailedEx = e;
        continue;
      }
      LOG.debug("Login success via [LDAP] for: {} at {}", username, request.getRemoteAddr());
      CommonProfile profile = credentials.getUserProfile();
      profile.setId(username);
      String generate = jwtGenerator.generate(profile);
      response.addHeader("Set-Cookie", "nna-jwt-token=" + generate);
      currentUser.set(username);
      return true;
    }

    if (authFailedEx != null) {
      LOG.info("Login failed via [LDAP] for: {}", request.getRemoteAddr());
      throw authFailedEx;
    }
  }
  return false;
}
 
Example #6
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public CommonProfile apply(ContainerRequest containerRequest) {
    return optionalProfile(containerRequest)
        .orElseThrow(() -> {
            LOG.debug("Cannot inject a Pac4j profile into an unauthenticated request, responding with 401");
            return new WebApplicationException(401);
        });
}
 
Example #7
Source File: TestResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@POST
@Path("directInject")
@Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED)
public String directInject(@Pac4JProfile CommonProfile profile) {
    if (profile != null) {
        return "ok";
    } else {
        return "error";
    }
}
 
Example #8
Source File: TestResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@GET
@Path("directInjectNoAuth")
public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) {
    if (profile != null) {
        return "ok";
    } else {
        return "error";
    }
}
 
Example #9
Source File: TestResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@POST
@Path("directInjectManager")
@Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true)
public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction {
    if (pm != null) {
        // pm.isAuthorized is relying on the session...
        if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) {
            return "ok";
        } else {
            return "fail";
        }
    } else {
        return "error";
    }
}
 
Example #10
Source File: TestResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@POST
@Path("directInjectSkip")
@Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true)
public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) {
    if (profile.isPresent()) {
        return "ok";
    } else {
        return "fail";
    }
}
 
Example #11
Source File: TestSessionResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/inject")
@Pac4JSecurity(clients = "FormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED)
public String inject(@Pac4JProfile CommonProfile profile) {
    if (profile != null) {
        return "ok";
    } else {
        return "error";
    }
}
 
Example #12
Source File: JaxRsProfileManager.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
public Pac4JSecurityContext(SecurityContext original, JaxRsContext context,
        Collection<CommonProfile> profiles) {
    this.original = original;
    this.context = context;
    this.profiles = profiles;
    this.principal = ProfileHelper.flatIntoOneProfile(profiles).map(Pac4JPrincipal::new).orElse(null);
}
 
Example #13
Source File: JaxRsProfileManager.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
public Optional<Collection<CommonProfile>> getProfiles() {
    if (principal != null) {
        return Optional.of(Collections.unmodifiableCollection(profiles));
    } else if (original instanceof Pac4JSecurityContext) {
        return ((Pac4JSecurityContext) original).getProfiles();
    } else {
        return Optional.empty();
    }
}
 
Example #14
Source File: CommonAspect.java    From spring-webmvc-pac4j with Apache License 2.0 5 votes vote down vote up
protected List<CommonProfile> isAuthenticated(final boolean readFromSession) {
    final List<CommonProfile> profiles = profileManager.getAll(readFromSession);

    if (!IS_AUTHENTICATED_AUTHORIZER.isAuthorized(webContext, profiles)) {
        throw UnauthorizedAction.INSTANCE;
    }
    return profiles;
}
 
Example #15
Source File: CommonAspect.java    From spring-webmvc-pac4j with Apache License 2.0 5 votes vote down vote up
protected void requireAnyRole(final boolean readFromSession, final String... roles) {
    final List<CommonProfile> profiles = isAuthenticated(readFromSession);

    final RequireAnyRoleAuthorizer<CommonProfile> authorizer = new RequireAnyRoleAuthorizer<>(roles);
    if (!authorizer.isAuthorized(webContext, profiles)) {
        throw ForbiddenAction.INSTANCE;
    }
}
 
Example #16
Source File: CommonAspect.java    From spring-webmvc-pac4j with Apache License 2.0 5 votes vote down vote up
protected void requireAllRoles(final boolean readFromSession, final String... roles) {
    final List<CommonProfile> profiles = isAuthenticated(readFromSession);

    final RequireAllRolesAuthorizer<CommonProfile> authorizer = new RequireAllRolesAuthorizer<>(roles);
    if (!authorizer.isAuthorized(webContext, profiles)) {
        throw ForbiddenAction.INSTANCE;
    }
}
 
Example #17
Source File: VertxProfileManager.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void saveAll(final LinkedHashMap<String, CommonProfile> profiles, final boolean saveInSession) {
    super.saveAll(profiles, saveInSession);

    final Pac4jUser vertxUser = Optional.ofNullable(vertxWebContext.getVertxUser()).orElse(new Pac4jUser());
    vertxUser.setUserProfiles(profiles);
    vertxWebContext.setVertxUser(vertxUser);
}
 
Example #18
Source File: Pac4jIdentityAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
    throws IOException, ServletException {

  final HttpServletRequest request = (HttpServletRequest) servletRequest;
  final HttpServletResponse response = (HttpServletResponse) servletResponse;
  final J2EContext context = new J2EContext(request, response,
      ((Config)request.getAttribute(PAC4J_CONFIG)).getSessionStore());
  final ProfileManager<CommonProfile> manager = new ProfileManager<>(context);
  final Optional<CommonProfile> optional = manager.get(true);
  if (optional.isPresent()) {
    CommonProfile profile = optional.get();
    logger.debug("User authenticated as: {}", profile);
    manager.remove(true);
    String id = null;
    if (idAttribute != null) {
      Object attribute = profile.getAttribute(idAttribute);
      if (attribute != null) {
        id = attribute.toString();
      }
      if (id == null) {
        logger.error("Invalid attribute_id: {} configured to be used as principal"
            + " falling back to default id", idAttribute);
      }
    }
    if (id == null) {
      id = profile.getId();
    }
    testIdentifier = id;
    PrimaryPrincipal pp = new PrimaryPrincipal(id);
    Subject subject = new Subject();
    subject.getPrincipals().add(pp);
    auditService.getContext().setUsername(id);
    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
    auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);

    doAs(request, response, chain, subject);
  }
}
 
Example #19
Source File: RegisterPage.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
public RegisterPage(PageParameters parameters) {
	super(parameters);
	
	if (AuthenticatedWebSession.exists() && AuthenticatedWebSession.get().isSignedIn()) {
		redirect(DashboardPage.class);
		return;
	}
	
	HttpServletRequest request = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest();
	ClientAuthenticationToken token = (ClientAuthenticationToken) request.getSession().getAttribute(Pac4jAuthenticationUtils.AUTH_TOKEN_ATTRIBUTE);
	
	IModel<User> userModel = new GenericEntityModel<Long, User>(new User());
	
	if (token != null && token.getUserProfile() != null) {
		CommonProfile profile = (CommonProfile) token.getUserProfile();
		if (profile.getEmail() != null) {
			User user = userService.getByUserName(profile.getEmail());
			if (user != null) {
				LOGGER.warn("This email address is already used by another user");
				getSession().warn(getString("register.userName.notUnique"));
			}
		}
		
		userModel.getObject().setEmail(profile.getEmail());
		userModel.getObject().setFullName(profile.getDisplayName());
		userModel.getObject().setRemoteIdentifier(profile.getId());
	}

	addBreadCrumbElement(new BreadCrumbElement(new ResourceModel("register.pageTitle"), RegisterPage.linkDescriptor()));
	
	add(new Label("pageTitle", new ResourceModel("register.pageTitle")));
	
	add(new RegisterFormPanel("registerFormPanel", userModel));
}
 
Example #20
Source File: Pac4jUserDetailsService.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserDetails(ClientAuthenticationToken token) throws UsernameNotFoundException {
	CommonProfile commonProfile = (CommonProfile) token.getUserProfile();
	
	IGroupedUser<?> person = userService.getByRemoteIdentifier(commonProfile.getId());
	
	if (person == null) {
		throw new UsernameNotFoundException("User not found for: " + token.getPrincipal());
	}
	
	if (!person.isActive()) {
		throw new DisabledException("User is disabled");
	}
	
	Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
	
	addAuthorities(grantedAuthorities, person.getAuthorities());
	
	for (IUserGroup personGroup : person.getGroups()) {
		addAuthorities(grantedAuthorities, personGroup.getAuthorities());
	}
	
	User userDetails = new User(person.getUserName(), person.getPasswordHash(), person.isActive(), true, true, true, 
			roleHierarchy.getReachableGrantedAuthorities(grantedAuthorities));
	
	return userDetails;
}
 
Example #21
Source File: SecurityContext.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
/**
 * Perform logout of authenticated web session.
 *
 * @param request - The HTTP request.
 * @param response - The HTTP response.
 */
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
  boolean authenticationEnabled = isAuthenticationEnabled();
  ProfileManager<CommonProfile> manager = new ProfileManager<>(new J2EContext(request, response));
  Optional<CommonProfile> profile = manager.get(false);
  if (authenticationEnabled && profile.isPresent()) {
    manager.logout();
    HttpSession session = request.getSession();
    if (session != null) {
      session.invalidate();
    }
    Cookie cookie = new Cookie("nna-jwt-token", "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Expires", "0");
    response.setStatus(HttpStatus.SC_OK);
    try (Writer writer = response.getWriter()) {
      writer.write("You have been logged out.");
    }
  } else {
    response.setStatus(HttpStatus.SC_BAD_REQUEST);
    try (Writer writer = response.getWriter()) {
      writer.write("No login session.");
    }
  }
}
 
Example #22
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Factory<?> createValueFactory(Parameter parameter) {
    if (parameter.isAnnotationPresent(Pac4JProfileManager.class)) {
        if (ProfileManager.class.isAssignableFrom(parameter.getRawType())) {
            return manager.get();
        }

        throw new IllegalStateException("Cannot inject a Pac4J profile manager into a parameter of type "
                + parameter.getRawType().getName());
    }

    if (parameter.isAnnotationPresent(Pac4JProfile.class)) {
        if (CommonProfile.class.isAssignableFrom(parameter.getRawType())) {
            return profile.get();
        }

        if (Optional.class.isAssignableFrom(parameter.getRawType())) {
            List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(parameter.getRawType());
            ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null;
            if (ctp == null || CommonProfile.class.isAssignableFrom(ctp.rawClass())) {
                return optProfile.get();
            }
        }

        throw new IllegalStateException(
                "Cannot inject a Pac4J profile into a parameter of type " + parameter.getRawType().getName());
    }

    return null;
}
 
Example #23
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Function<ContainerRequest, ?> createValueProvider(Parameter parameter) {
    if (parameter.isAnnotationPresent(Pac4JProfileManager.class)) {
        if (ProfileManager.class.isAssignableFrom(parameter.getRawType())) {
            return manager.get();
        }

        throw new IllegalStateException("Cannot inject a Pac4J profile manager into a parameter of type "
            + parameter.getRawType().getName());
    }

    if (parameter.isAnnotationPresent(Pac4JProfile.class)) {
        if (CommonProfile.class.isAssignableFrom(parameter.getRawType())) {
            return profile.get();
        }

        if (Optional.class.isAssignableFrom(parameter.getRawType())) {
            List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(parameter.getRawType());
            ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null;
            if (ctp == null || CommonProfile.class.isAssignableFrom(ctp.rawClass())) {
                return optProfile.get();
            }
        }

        throw new IllegalStateException(
            "Cannot inject a Pac4J profile into a parameter of type " + parameter.getRawType().getName());
    }

    return null;
}
 
Example #24
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public CommonProfile provide() {
    return new RequestCommonProfile(new RequestPac4JSecurityContext(getContainerRequest())).profile()
            .orElseThrow(() -> {
                LOG.debug("Cannot inject a Pac4j profile into an unauthenticated request, responding with 401");
                return new WebApplicationException(401);
            });
}
 
Example #25
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public CommonProfile apply(ContainerRequest containerRequest) {
    return optionalProfile(containerRequest)
        .orElseThrow(() -> {
            LOG.debug("Cannot inject a Pac4j profile into an unauthenticated request, responding with 401");
            return new WebApplicationException(401);
        });
}
 
Example #26
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
@Override
public ProfileManager<CommonProfile> provide() {
    return new RequestProfileManager(new RequestJaxRsContext(providers, getContainerRequest()))
            .profileManager();
}
 
Example #27
Source File: SecurityContext.java    From NNAnalytics with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures that user request has proper authentication token / credentials.
 *
 * @param request the HTTP request
 * @param response the HTTP response
 * @throws AuthenticationException error with authentication
 * @throws HttpAction error with HTTP call
 */
public void handleAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, HttpAction {
  if (!init) {
    LOG.info("Request occurred before initialized from: {}", request.getRemoteAddr());
    throw new AuthenticationException("Please wait for initialization.");
  }

  if (isLoginAttempt(request)) {
    return;
  }

  boolean authenticationEnabled = isAuthenticationEnabled();
  if (!authenticationEnabled) {
    String proxyUsername = request.getParameter("proxy");
    if (proxyUsername != null && !proxyUsername.isEmpty()) {
      currentUser.set(proxyUsername);
    }
    return;
  }

  // Allow basic authentication for simple applications.
  String basic = request.getHeader("Authorization");
  if (basic != null && basic.startsWith("Basic ")) {
    String b64Credentials = basic.substring("Basic ".length()).trim();
    String nameAndPassword =
        new String(Base64.getDecoder().decode(b64Credentials), Charset.defaultCharset());
    String[] split = nameAndPassword.split(":");
    String username = split[0];
    String password = (split.length == 1) ? "" : split[1];
    // Perform local authentication if found.
    if (localLogin(request, response, username, password)) {
      return;
    }
    // Perform LDAP authentication if found.
    if (ldapLogin(request, response, username, password)) {
      return;
    }
    LOG.info("Login failed via [BASIC] for: {}", request.getRemoteAddr());
    throw new AuthenticationException("Authentication required.");
  }

  // JWT authentication for end users whom have logged in.
  String token = null;
  Cookie[] cookies = request.getCookies();
  if (cookies != null) {
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("nna-jwt-token")) {
        token = cookie.getValue();
        break;
      }
    }
  }

  ProfileManager<CommonProfile> manager = new ProfileManager<>(new J2EContext(request, response));
  CommonProfile userProfile;
  if (token != null) {
    try {
      userProfile = jwtAuthenticator.validateToken(token);

      userProfile.removeAttribute("iat");
      String generate = jwtGenerator.generate(userProfile);
      response.addHeader("Set-Cookie", "nna-jwt-token=" + generate);

      manager.save(true, userProfile, false);
      String profileId = userProfile.getId();
      LOG.debug("Login success via [TOKEN] for: {} at {}", profileId, request.getRemoteAddr());
      currentUser.set(profileId);
      return;
    } catch (Exception e) {
      LOG.info("Login failed via [TOKEN] for: {}", request.getRemoteAddr());
      throw new AuthenticationException(e);
    }
  }

  LOG.info("Login failed via [NULL] for: {}", request.getRemoteAddr());
  throw new AuthenticationException("Authentication required.");
}
 
Example #28
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    logger.debug("clientName: {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.debug("client: {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.debug("credentials: {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.debug("requires http action: {}", e);
            response.flushBuffer();
            final ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.debug("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            final TicketGrantingTicket tgt = 
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials));
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}
 
Example #29
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    //final String clientName = request.getParameter(this.clients.getClientNameParameter());
    final String clientName = request.getParameter("state");
    //logger.debug("clientName : {}", clientName);
    logger.info("clientName : {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.info("client : {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        logger.info("mechanism == " + mechanism.name());
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.info("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.info("requires http action : {}", e);
            response.flushBuffer();
            ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.info("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            logger.info("credentials is not null : {}", credentials);
            WebUtils.putTicketGrantingTicketInRequestScope(context,
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials)));
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}
 
Example #30
Source File: Pac4jUser.java    From vertx-pac4j with Apache License 2.0 4 votes vote down vote up
public void setUserProfiles(final Map<String, CommonProfile> userProfiles) {
    Objects.requireNonNull(userProfiles);
    profiles.clear();
    profiles.putAll(userProfiles);
    updatePrincipal();
}