Search in sources :

Example 16 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class SessionsResource method terminateSession.

@DELETE
@ApiOperation(value = "Terminate an existing session", notes = "Destroys the session with the given ID: the equivalent of logging out.")
@Path("/{sessionId}")
@RequiresAuthentication
@AuditEvent(type = AuditEventTypes.SESSION_DELETE)
public void terminateSession(@ApiParam(name = "sessionId", required = true) @PathParam("sessionId") String sessionId) {
    final Subject subject = getSubject();
    securityManager.logout(subject);
}
Also used : Subject(org.apache.shiro.subject.Subject) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) AuditEvent(org.graylog2.audit.jersey.AuditEvent)

Example 17 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class SessionsResource method newSession.

@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public SessionResponse newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Username and credentials", required = true) @Valid @NotNull SessionCreateRequest createRequest) {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (!(securityContext instanceof ShiroSecurityContext)) {
        throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
    }
    final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    // pretend that we had session id before
    Serializable id = null;
    if (sessionId != null && !sessionId.isEmpty()) {
        id = sessionId;
    }
    final String remoteAddrFromRequest = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
    ThreadContext.bind(subject);
    final Session s = subject.getSession();
    try {
        subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
        final User user = userService.load(createRequest.username());
        if (user != null) {
            long timeoutInMillis = user.getSessionTimeoutMs();
            s.setTimeout(timeoutInMillis);
        } else {
            // set a sane default. really we should be able to load the user from above.
            s.setTimeout(TimeUnit.HOURS.toMillis(8));
        }
        s.touch();
        // save subject in session, otherwise we can't get the username back in subsequent requests.
        ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
    } catch (AuthenticationException e) {
        LOG.info("Invalid username or password for user \"{}\"", createRequest.username());
    } catch (UnknownSessionException e) {
        subject.logout();
    }
    if (subject.isAuthenticated()) {
        id = s.getId();
        final Map<String, Object> auditEventContext = ImmutableMap.of("session_id", id, "remote_address", remoteAddrFromRequest);
        auditEventSender.success(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        // TODO is the validUntil attribute even used by anyone yet?
        return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(), id.toString());
    } else {
        final Map<String, Object> auditEventContext = ImmutableMap.of("remote_address", remoteAddrFromRequest);
        auditEventSender.failure(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        throw new NotAuthorizedException("Invalid username or password", "Basic realm=\"Graylog Server session\"");
    }
}
Also used : Serializable(java.io.Serializable) User(org.graylog2.plugin.database.users.User) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownSessionException(org.apache.shiro.session.UnknownSessionException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) DateTime(org.joda.time.DateTime) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 18 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class SessionsResource method validateSession.

@GET
@ApiOperation(value = "Validate an existing session", notes = "Checks the session with the given ID: returns http status 204 (No Content) if session is valid.", code = 204)
public SessionValidationResponse validateSession(@Context ContainerRequestContext requestContext) {
    try {
        this.authenticationFilter.filter(requestContext);
    } catch (NotAuthorizedException | LockedAccountException | IOException e) {
        return SessionValidationResponse.invalid();
    }
    final Subject subject = getSubject();
    if (!subject.isAuthenticated()) {
        return SessionValidationResponse.invalid();
    }
    // there's no valid session, but the authenticator would like us to create one
    if (subject.getSession(false) == null && ShiroSecurityContext.isSessionCreationRequested()) {
        final Session session = subject.getSession();
        LOG.debug("Session created {}", session.getId());
        session.touch();
        // save subject in session, otherwise we can't get the username back in subsequent requests.
        ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
        return SessionValidationResponse.validWithNewSession(String.valueOf(session.getId()), String.valueOf(subject.getPrincipal()));
    }
    return SessionValidationResponse.valid();
}
Also used : NotAuthorizedException(javax.ws.rs.NotAuthorizedException) IOException(java.io.IOException) LockedAccountException(org.apache.shiro.authc.LockedAccountException) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 19 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class ShiroPrincipalTest method testGetSubject.

@Test
public void testGetSubject() throws Exception {
    final Subject subject = mock(Subject.class);
    final ShiroPrincipal shiroPrincipal = new ShiroPrincipal(subject);
    assertThat(shiroPrincipal.getSubject()).isSameAs(subject);
}
Also used : Subject(org.apache.shiro.subject.Subject) Test(org.junit.Test)

Example 20 with Subject

use of org.apache.shiro.subject.Subject in project graylog2-server by Graylog2.

the class ShiroPrincipalTest method testGetName.

@Test
public void testGetName() throws Exception {
    final Subject subject = mock(Subject.class);
    when(subject.getPrincipal()).thenReturn("test");
    final ShiroPrincipal shiroPrincipal = new ShiroPrincipal(subject);
    assertThat(shiroPrincipal.getName()).isEqualTo("test");
}
Also used : Subject(org.apache.shiro.subject.Subject) Test(org.junit.Test)

Aggregations

Subject (org.apache.shiro.subject.Subject)78 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)11 Test (org.junit.Test)9 IOException (java.io.IOException)8 Map (java.util.Map)8 Path (javax.ws.rs.Path)8 StopProcessingException (ddf.catalog.plugin.StopProcessingException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 AccountVO (com.netsteadfast.greenstep.vo.AccountVO)5 Attribute (ddf.catalog.data.Attribute)5 KeyValueCollectionPermission (ddf.security.permission.KeyValueCollectionPermission)5 GET (javax.ws.rs.GET)5 AuthenticationException (org.apache.shiro.authc.AuthenticationException)5 ServiceException (com.netsteadfast.greenstep.base.exception.ServiceException)4 Metacard (ddf.catalog.data.Metacard)4 ApiOperation (io.swagger.annotations.ApiOperation)4 POST (javax.ws.rs.POST)4 PersistenceException (org.codice.ddf.persistence.PersistenceException)4