org.pac4j.core.context.J2EContext Java Examples

The following examples show how to use org.pac4j.core.context.J2EContext. 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: IndexController.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * app rest 登录获取token
 * eg:http://localhost:8081/user/login?cilent_name=rest&username=hsjhsj&password=hsjhsj
 * 然后获取资源:http://localhost:8081/user/1?token=eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..7usGh1GK3jl5_wPH.QJdYqNp81zRyAs6OHmN4573l67z_UgxQ7WXJ7OUsDw50Dato2X9Tyh5kXBAJF5l9LmmKe8y-kHrhyx9gcEIa6PC97mo5fPbCw9WoOypyTqdWkE1Q9mM44Zn8CZZVH9PTml7_0jwln0W_bzDWjN3f-0Pk2etxU6lXwz5insFVz4nGt5SEmykhvOdKlscLsYbHGQVqze4nlXuAtVXQ08CuphRsZ2FmSaK-LFR8Ivs.DkqbT-PgEjE0ZS6pgNVqGA
 * @Description:TODO
 * @author:hsj qq:2356899074
 * @time:2017年12月11日 下午2:36:30
 * @param request
 * @param response
 * @return
 */
@RequestMapping("/user/login")
public Object login(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> model = new HashMap<>();
    J2EContext context = new J2EContext(request, response);
    final ProfileManager<CasRestProfile> manager = new ProfileManager(context);
    final Optional<CasRestProfile> profile = manager.get(true);
    //获取ticket
    TokenCredentials tokenCredentials = casRestFormClient.requestServiceTicket(serviceUrl, profile.get(), context);
    //根据ticket获取用户信息
    final CasProfile casProfile = casRestFormClient.validateServiceTicket(serviceUrl, tokenCredentials, context);
    //生成jwt token
    String token = generator.generate(casProfile);
    model.put("token", token);
    return new HttpEntity<>(model);
}
 
Example #2
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    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);

    // save parameters in web session
    final WebApplicationService service = WebUtils.getService(context);
    logger.debug("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.debug("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #3
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    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);

    // save parameters in web session
    final Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #4
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 #5
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 #6
Source File: AbstractClientAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("clientCredentials : {}", clientCredentials);

    final Credentials credentials = clientCredentials.getCredentials();
    final String clientName = credentials.getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<Credentials, UserProfile> client = this.clients.findClient(clientName);
    logger.debug("client : {}", client);

    // web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);
    
    // get user profile
    final UserProfile userProfile = client.getUserProfile(credentials, webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null) {
        return createResult(clientCredentials, userProfile);
    }

    throw new FailedLoginException("Provider did not produce a user profile for: " + clientCredentials);
}
 
Example #7
Source File: ClientAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("clientCredentials : {}", clientCredentials);

    final String clientName = clientCredentials.getCredentials().getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<org.pac4j.core.credentials.Credentials, UserProfile> client = this.clients.findClient(clientName);
    logger.debug("client : {}", client);

    // web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);

    // get user profile
    final UserProfile userProfile = client.getUserProfile(clientCredentials.getCredentials(), webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null && StringUtils.isNotBlank(userProfile.getTypedId())) {
        clientCredentials.setUserProfile(userProfile);
        return new HandlerResult(
                this,
                new BasicCredentialMetaData(credential),
                new SimplePrincipal(userProfile.getTypedId(), userProfile.getAttributes()));
    }

    throw new FailedLoginException("Provider did not produce profile for " + clientCredentials);
}
 
Example #8
Source File: IndexController.java    From wolf with MIT License 5 votes vote down vote up
@RequestMapping("/user/login")
public Object login(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> model = new HashMap<>();
    J2EContext context = new J2EContext(request, response);
    final ProfileManager<CasRestProfile> manager = new ProfileManager(context);
    final Optional<CasRestProfile> profile = manager.get(true);
    //获取ticket
    TokenCredentials tokenCredentials = casRestFormClient.requestServiceTicket(serviceUrl, profile.get(), context);
    //根据ticket获取用户信息
    final CasProfile casProfile = casRestFormClient.validateServiceTicket(serviceUrl, tokenCredentials, context);
    //生成jwt token
    String token = generator.generate(casProfile);
    model.put("token", token);
    return new HttpEntity<>(model);
}
 
Example #9
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 #10
Source File: Pac4jAuthenticationUtils.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
public static String getClientRedirectUrl(Pac4jClient client) {
	BaseClient<?, ?> baseClient = (BaseClient<?, ?>) WebApplication.get().getServletContext().getAttribute(client.getClientKey());
	HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
	HttpServletResponse response = (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse();
	
	return baseClient.getRedirectionUrl(new J2EContext(request, response));
}
 
Example #11
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 #12
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 #13
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();
}