org.jasig.cas.authentication.Credential Java Examples
The following examples show how to use
org.jasig.cas.authentication.Credential.
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: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
@Override protected Credential constructCredentialsFromRequest( final RequestContext context) { final HttpServletRequest request = WebUtils .getHttpServletRequest(context); final Principal principal = request.getUserPrincipal(); if (principal != null) { logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName()); return new PrincipalBearingCredential(new SimplePrincipal( principal.getName())); } logger.debug("UserPrincipal not found in HttpServletRequest."); return null; }
Example #2
Source File: KryoTranscoderTests.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
public MockTicketGrantingTicket(final String id, final Credential credential, final Map<String, Object> principalAttributes) { this.id = id; final CredentialMetaData credentialMetaData = new BasicCredentialMetaData(credential); final DefaultAuthenticationBuilder builder = new DefaultAuthenticationBuilder(); builder.setPrincipal(this.principalFactory.createPrincipal(USERNAME, principalAttributes)); builder.setAuthenticationDate(new Date()); builder.addCredential(credentialMetaData); builder.addAttribute(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, Boolean.TRUE); final AuthenticationHandler handler = new MockAuthenticationHandler(); try { builder.addSuccess(handler.getName(), handler.authenticate(credential)); } catch (final Exception e) { throw new RuntimeException(e); } builder.addFailure(handler.getName(), FailedLoginException.class); this.authentication = builder.build(); }
Example #3
Source File: GenerateMultiFactorCredentialsActionTests.java From cas-mfa with Apache License 2.0 | 6 votes |
@Test public void testAuthenticationViaTGT() { setMockAuthenticationContextWith(null); setMockTgtContextWith(TGT_ID); final Credential c = getCredentials(); when(this.sessionFlowScope.getRequired(anyString(), any(UsernamePasswordCredentials.class.getClass()))).thenReturn(c); when(this.requestContext.getFlowScope().get("credential")).thenReturn(c); final Event event = this.action.doExecute(this.requestContext); final Credential creds = (Credential) event.getAttributes().get(GenerateMultiFactorCredentialsAction.ATTRIBUTE_ID_MFA_CREDENTIALS); assertTrue(creds instanceof MultiFactorCredentials); final MultiFactorCredentials mfaCreds = (MultiFactorCredentials) creds; assertEquals(mfaCreds.countChainedAuthentications(), 1); assertEquals(mfaCreds.getChainedCredentials().size(), 1); assertEquals(mfaCreds.getAuthentication().getPrincipal().getId(), authentication.getPrincipal().getId()); assertEquals(mfaCreds.getCredentials(), c); }
Example #4
Source File: AuthenticationViaFormActionTests.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
@Test public void verifyRenewWithServiceAndDifferentCredentials() throws Exception { final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword(); final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockRequestContext context = new MockRequestContext(); WebUtils.putLoginTicket(context, "LOGIN"); request.addParameter("lt", "LOGIN"); WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket); request.addParameter("renew", "true"); request.addParameter("service", "test"); request.addParameter("username", "test2"); request.addParameter("password", "test2"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); final MessageContext messageContext = mock(MessageContext.class); assertEquals("success", this.action.submit(context, c, messageContext).getId()); }
Example #5
Source File: TicketResource.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
/** * Obtain credentials from the request. * * @return the credential */ protected Credential obtainCredentials() { final UsernamePasswordCredential c = new UsernamePasswordCredential(); final WebRequestDataBinder binder = new WebRequestDataBinder(c); final RestletWebRequest webRequest = new RestletWebRequest(getRequest()); final Form form = new Form(getRequest().getEntity()); logFormRequest(form); if (!form.isEmpty()) { binder.bind(webRequest); return c; } LOGGER.trace("Failed to bind the request to credentials. Resulting form is empty"); return null; }
Example #6
Source File: CacheCredentialsMetaDataPopulatorTests.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
@Test public void verifyAttributePopulationWithPasswordWithDifferentCredentialsType() { final Authentication auth = TestUtils.getAuthentication(); final Map<String, String> map = new HashMap<>(); final CacheCredentialsMetaDataPopulator populator = new CacheCredentialsMetaDataPopulator(map); final Credential c = new Credential() { @Override public String getId() { return "something"; } }; if (populator.supports(c)) { populator.populateAttributes(DefaultAuthenticationBuilder.newInstance(auth), c); } assertEquals(map.size(), 0); }
Example #7
Source File: OpenIdCredentialsAuthenticationHandler.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
@Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException { final OpenIdCredential c = (OpenIdCredential) credential; final TicketGrantingTicket t = this.ticketRegistry.getTicket(c.getTicketGrantingTicketId(), TicketGrantingTicket.class); if (t == null || t.isExpired()) { throw new FailedLoginException("TGT is null or expired."); } final Principal principal = t.getAuthentication().getPrincipal(); if (!principal.getId().equals(c.getUsername())) { throw new FailedLoginException("Principal ID mismatch"); } return new HandlerResult(this, new BasicCredentialMetaData(c), principal); }
Example #8
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
@Override protected Credential constructCredentialsFromRequest( final RequestContext context) { final HttpServletRequest request = WebUtils .getHttpServletRequest(context); final Principal principal = request.getUserPrincipal(); if (principal != null) { logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName()); return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName())); } logger.debug("UserPrincipal not found in HttpServletRequest."); return null; }
Example #9
Source File: ChainingPrincipalResolverTest.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
@Test public void examineResolve() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("input"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); when(resolver1.resolve((eq(credential)))).thenReturn(principalFactory.createPrincipal("output")); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(any(Credential.class))).thenReturn(false); when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() { @Override public boolean matches(final Object o) { return "output".equals(((Credential) o).getId()); } }))).thenReturn(principalFactory.createPrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]"))); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); final Principal principal = resolver.resolve(credential); assertEquals("final", principal.getId()); assertEquals("[email protected]", principal.getAttributes().get("mail")); }
Example #10
Source File: TicketOrCredentialPrincipalResolver.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
protected String resolveFromInternal(final JoinPoint joinPoint) { final Object arg1 = joinPoint.getArgs()[0]; if (arg1 instanceof Credential) { return arg1.toString(); } else if (arg1 instanceof String) { final Ticket ticket = this.ticketRegistry.getTicket((String) arg1); if (ticket instanceof ServiceTicket) { final ServiceTicket serviceTicket = (ServiceTicket) ticket; return serviceTicket.getGrantingTicket().getAuthentication().getPrincipal().getId(); } else if (ticket instanceof TicketGrantingTicket) { final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket; return tgt.getAuthentication().getPrincipal().getId(); } } else { final SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null) { final Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { return ((UserDetails) authentication.getPrincipal()).getUsername(); } } } return UNKNOWN_USER; }
Example #11
Source File: SimpleTestUsernamePasswordAuthenticationHandler.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
@Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException { final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential; final String username = usernamePasswordCredential.getUsername(); final String password = usernamePasswordCredential.getPassword(); final Exception exception = this.usernameErrorMap.get(username); if (exception instanceof GeneralSecurityException) { throw (GeneralSecurityException) exception; } else if (exception instanceof PreventedException) { throw (PreventedException) exception; } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else if (exception != null) { logger.debug("Cannot throw checked exception {} since it is not declared by method signature.", exception); } if (StringUtils.hasText(username) && StringUtils.hasText(password) && username.equals(password)) { logger.debug("User [{}] was successfully authenticated.", username); return new DefaultHandlerResult(this, new BasicCredentialMetaData(credential)); } logger.debug("User [{}] failed authentication", username); throw new FailedLoginException(); }
Example #12
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
@Override protected Credential constructCredentialsFromRequest( final RequestContext context) { final HttpServletRequest request = WebUtils .getHttpServletRequest(context); final String remoteUser = request.getRemoteUser(); if (StringUtils.hasText(remoteUser)) { logger.debug("Remote User [{}] found in HttpServletRequest", remoteUser); return new PrincipalBearingCredential(new SimplePrincipal(remoteUser)); } logger.debug("Remote User not found in HttpServletRequest."); return null; }
Example #13
Source File: ClientActionTests.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Test public void verifyFinishAuthentication() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient"); final MockHttpSession mockSession = new MockHttpSession(); mockSession.setAttribute(ClientAction.THEME, MY_THEME); mockSession.setAttribute(ClientAction.LOCALE, MY_LOCALE); mockSession.setAttribute(ClientAction.METHOD, MY_METHOD); final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE); mockSession.setAttribute(ClientAction.SERVICE, service); mockRequest.setSession(mockSession); final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class); when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest); final MockRequestContext mockRequestContext = new MockRequestContext(); mockRequestContext.setExternalContext(servletExternalContext); final FacebookClient facebookClient = new MockFacebookClient(); final Clients clients = new Clients(MY_LOGIN_URL, facebookClient); final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class), mock(ExpirationPolicy.class)); final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class); when(casImpl.createTicketGrantingTicket(any(Credential.class))).thenReturn(tgt); final ClientAction action = new ClientAction(casImpl, clients); final Event event = action.execute(mockRequestContext); assertEquals("success", event.getId()); assertEquals(MY_THEME, mockRequest.getAttribute(ClientAction.THEME)); assertEquals(MY_LOCALE, mockRequest.getAttribute(ClientAction.LOCALE)); assertEquals(MY_METHOD, mockRequest.getAttribute(ClientAction.METHOD)); assertEquals(MY_SERVICE, mockRequest.getAttribute(ClientAction.SERVICE)); final MutableAttributeMap flowScope = mockRequestContext.getFlowScope(); final MutableAttributeMap requestScope = mockRequestContext.getRequestScope(); assertEquals(service, flowScope.get(ClientAction.SERVICE)); assertEquals(TGT_ID, flowScope.get(TGT_NAME)); assertEquals(TGT_ID, requestScope.get(TGT_NAME)); }
Example #14
Source File: ChainingPrincipalResolver.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
/** * Resolves a credential by delegating to each of the configured resolvers in sequence. Note that the * {@link PrincipalResolver#supports(org.jasig.cas.authentication.Credential)} method is called only for the * first configured resolver. * * @param credential Authenticated credential. * * @return The principal from the last configured resolver in the chain. */ public Principal resolve(final Credential credential) { Principal result = null; Credential input = credential; for (final PrincipalResolver resolver : this.chain) { if (result != null) { input = new IdentifiableCredential(result.getId()); } result = resolver.resolve(input); } return result; }
Example #15
Source File: ClientAuthenticationHandler.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
@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 #16
Source File: AbstractMultiFactorAuthenticationViaFormAction.java From cas-mfa with Apache License 2.0 | 5 votes |
@Override protected final Event doExecute(final RequestContext ctx) throws Exception { final Credential credentials = WebUtils.getCredential(ctx); final MessageContext messageContext = ctx.getMessageContext(); if (credentials != null) { final String id = credentials.getId(); return submit(ctx, credentials, messageContext, id); } logger.warn("Credentials could not be determined, or no username was associated with the request."); return getErrorEvent(ctx); }
Example #17
Source File: MultiFactorCredentials.java From cas-mfa with Apache License 2.0 | 5 votes |
@Override public String getId() { if (getPrincipal() != null) { return getPrincipal().getId(); } return Credential.UNKNOWN_ID; }
Example #18
Source File: KryoTranscoderTests.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Test public void verifyEncodeDecodeTGTWithSingletonMap() throws Exception { final Map<String, Object> newAttributes = Collections.singletonMap(NICKNAME_KEY, (Object) NICKNAME_VALUE); final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD); final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes); expectedTGT.grantServiceTicket(ST_ID, null, null, false); assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT))); }
Example #19
Source File: RemoteCentralAuthenticationServiceTests.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Test public void verifyGrantServiceTicketWithNullCredentials() throws Exception { final TicketGrantingTicket ticketGrantingTicketId = this.remoteCentralAuthenticationService .createTicketGrantingTicket(TestUtils .getCredentialsWithSameUsernameAndPassword()); this.remoteCentralAuthenticationService.grantServiceTicket( ticketGrantingTicketId.getId(), TestUtils.getService(), (Credential[]) null); }
Example #20
Source File: KryoTranscoderTests.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Test public void verifyEncodeDecode() throws Exception { final ServiceTicket expectedST = new MockServiceTicket(ST_ID); assertEquals(expectedST, transcoder.decode(transcoder.encode(expectedST))); final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD); final TicketGrantingTicket expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, this.principalAttributes); expectedTGT.grantServiceTicket(ST_ID, null, null, false); assertEquals(expectedTGT, transcoder.decode(transcoder.encode(expectedTGT))); internalProxyTest("http://localhost"); internalProxyTest("https://localhost:8080/path/file.html?p1=v1&p2=v2#fragment"); }
Example #21
Source File: SpnegoPrincipalResolver.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Override protected String extractPrincipalId(final Credential credential) { final SpnegoCredential c = (SpnegoCredential) credential; final String id = c.getPrincipal().getId(); switch (this.transformPrincipalId) { case UPPERCASE: return id.toUpperCase(Locale.ENGLISH); case LOWERCASE: return id.toLowerCase(Locale.ENGLISH); default: return id; } }
Example #22
Source File: RemoteCentralAuthenticationService.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
/** * {@inheritDoc} * @throws IllegalArgumentException if given invalid credentials */ @Override public ServiceTicket grantServiceTicket( final String ticketGrantingTicketId, final Service service, final Credential... credentials) throws AuthenticationException, TicketException { checkForErrors(credentials); return this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials); }
Example #23
Source File: TicketResource.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
protected Credential obtainCredentials() { final UsernamePasswordCredential c = new UsernamePasswordCredential(); final WebRequestDataBinder binder = new WebRequestDataBinder(c); final RestletWebRequest webRequest = new RestletWebRequest(getRequest()); logFormRequest(new Form(getRequest().getEntity())); binder.bind(webRequest); return c; }
Example #24
Source File: RemoteCentralAuthenticationService.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
/** * Check for errors by asking the validator to review each credential. * * @param credentials the credentials */ private void checkForErrors(final Credential... credentials) { if (credentials == null) { return; } for (final Credential c : credentials) { final Set<ConstraintViolation<Credential>> errors = this.validator.validate(c); if (!errors.isEmpty()) { throw new IllegalArgumentException("Error validating credentials: " + errors.toString()); } } }
Example #25
Source File: RemoteCentralAuthenticationService.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * @throws IllegalArgumentException if the Credentials are null or if given * invalid credentials. */ @Override public String createTicketGrantingTicket(final Credential... credentials) throws AuthenticationException, TicketException { Assert.notNull(credentials, "credentials cannot be null"); checkForErrors(credentials); return this.centralAuthenticationService.createTicketGrantingTicket(credentials); }
Example #26
Source File: PersonDirectoryPrincipalResolverTests.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
@Test public void verifyNoAttributesWithPrincipal() { final PersonDirectoryPrincipalResolver resolver = new PersonDirectoryPrincipalResolver(); resolver.setPrincipalAttributeName(TestUtils.CONST_USERNAME); final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword(); final Principal p = resolver.resolve(c); assertNotNull(p); }
Example #27
Source File: TestOneTimePasswordAuthenticationHandler.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
@Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException { final OneTimePasswordCredential otp = (OneTimePasswordCredential) credential; final String valueOnRecord = credentialMap.get(otp.getId()); if (otp.getPassword().equals(credentialMap.get(otp.getId()))) { return new HandlerResult(this, new BasicCredentialMetaData(otp), new SimplePrincipal(otp.getId())); } throw new FailedLoginException(); }
Example #28
Source File: CentralAuthenticationServiceImpl.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Audit( action="TICKET_GRANTING_TICKET", actionResolverName="CREATE_TICKET_GRANTING_TICKET_RESOLVER", resourceResolverName="CREATE_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER") @Timed(name = "CREATE_TICKET_GRANTING_TICKET_TIMER") @Metered(name = "CREATE_TICKET_GRANTING_TICKET_METER") @Counted(name="CREATE_TICKET_GRANTING_TICKET_COUNTER", monotonic=true) @Override public TicketGrantingTicket createTicketGrantingTicket(final Credential... credentials) throws AuthenticationException, TicketException { final Set<Credential> sanitizedCredentials = sanitizeCredentials(credentials); if (sanitizedCredentials.size() > 0) { final Authentication authentication = this.authenticationManager.authenticate(credentials); final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl( this.ticketGrantingTicketUniqueTicketIdGenerator .getNewTicketId(TicketGrantingTicket.PREFIX), authentication, this.ticketGrantingTicketExpirationPolicy); this.ticketRegistry.addTicket(ticketGrantingTicket); return ticketGrantingTicket; } final String msg = "No credentials were specified in the request for creating a new ticket-granting ticket"; logger.warn(msg); throw new TicketCreationException(new IllegalArgumentException(msg)); }
Example #29
Source File: RemoteCentralAuthenticationService.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * @throws IllegalArgumentException if given invalid credentials */ @Override public String grantServiceTicket( final String ticketGrantingTicketId, final Service service, final Credential... credentials) throws AuthenticationException, TicketException { checkForErrors(credentials); return this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials); }
Example #30
Source File: TicketOrCredentialPrincipalResolverTests.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Test public void verifyResolverCredential() { final TicketOrCredentialPrincipalResolver res = new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService()); final JoinPoint jp = mock(JoinPoint.class); final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword(); when(jp.getArgs()).thenReturn(new Object[] {c}); final String result = res.resolveFrom(jp, null); assertNotNull(result); assertEquals(result, c.toString()); }