org.pac4j.core.profile.ProfileManager Java Examples

The following examples show how to use org.pac4j.core.profile.ProfileManager. 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: Pac4jProducer.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method which produces a pac4j profile manager.
 *
 * @param webContext the web context to be used for building the profile manager
 * @return a profile manager associated with the current servlet request
 */
@Produces
ProfileManager getProfileManager(final WebContext webContext) {
    logger.trace("Producing a pac4j profile manager...");
    ProfileManager profileManager = new ProfileManager(webContext);
    logger.trace("Returning a pac4j profile manager.");
    return profileManager;
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: ComponentConfig.java    From spring-webmvc-pac4j with Apache License 2.0 4 votes vote down vote up
@Bean
@RequestScope
public ProfileManager getProfileManager() {
    return new ProfileManager<>(getWebContext());
}
 
Example #12
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
@Override
public ProfileManager<CommonProfile> apply(ContainerRequest containerRequest) {
    return new RequestProfileManager(new RequestJaxRsContext(providers, containerRequest))
        .profileManager();
}
 
Example #13
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
@Override
public ProfileManager<CommonProfile> apply(ContainerRequest containerRequest) {
    return new RequestProfileManager(new RequestJaxRsContext(providers, containerRequest))
        .profileManager();
}
 
Example #14
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
@Override
default void dispose(ProfileManager<CommonProfile> instance) {
    // do nothing
}
 
Example #15
Source File: Pac4jFactory.java    From dropwizard-pac4j with Apache License 2.0 4 votes vote down vote up
@JsonProperty
public Function<WebContext, ProfileManager> getProfileManagerFactory() {
    return profileManagerFactory;
}
 
Example #16
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 #17
Source File: Pac4jFactory.java    From dropwizard-pac4j with Apache License 2.0 2 votes vote down vote up
/**
 * @since 2.0.0
 * @param profileManagerFactory
 *            a class implementing a function from context to profile
 *            manager
 */
@JsonProperty
public void setProfileManagerFactory(
        Function<WebContext, ProfileManager> profileManagerFactory) {
    this.profileManagerFactory = profileManagerFactory;
}