Beispiel #1
0
    def authn_verify(self, url_endpoint, **kwargs):
        """
        Authentication verification

        :param url_endpoint: Which endpoint to use
        :param kwargs: response arguments
        :return: HTTP redirect
        """
        authn_method = self.endpoint_context.endpoint_to_authn_method[
            url_endpoint]

        username = authn_method.verify(**kwargs)
        if not username:
            raise cherrypy.HTTPError(403, message='Authentication failed')

        auth_args = authn_method.unpack_token(kwargs['token'])
        request = AuthorizationRequest().from_urlencoded(auth_args['query'])

        authn_event = create_authn_event(
            uid=username,
            salt='salt',
            authn_info=auth_args['authn_class_ref'],
            authn_time=auth_args['iat'])

        endpoint = self.endpoint_context.endpoint['authorization']
        args = endpoint.authz_part2(user=username,
                                    request=request,
                                    authn_event=authn_event)

        if isinstance(args, ResponseMessage):
            raise cherrypy.HTTPError(400, message=args.to_json())

        return do_response(endpoint, request, **args)
    def test_client_info_add2(self):
        user_info = UserSessionInfo(foo="bar")
        self.db.set(["diana"], user_info)
        client_info = ClientSessionInfo(sid="abcdef")
        self.db.set(["diana", "client_1"], client_info)

        # The reference is there but not the value
        del self.db.db[self.db.session_key("diana", "client_1")]

        authn_event = create_authn_event(uid="diana",
                                         expires_in=10,
                                         authn_info="authn_class_ref")

        grant = Grant(authentication_event=authn_event,
                      authorization_request=AUTHZ_REQ)

        access_code = SessionToken("access_code", value="1234567890")
        grant.issued_token.append(access_code)

        self.db.set(["diana", "client_1", "G1"], grant)
        stored_client_info = self.db.get(["diana", "client_1"])
        assert set(stored_client_info.keys()) == {
            "subordinate",
            "revoked",
            "type",
            "client_id",
            "extra_args",
        }

        stored_grant_info = self.db.get(["diana", "client_1", "G1"])
        assert stored_grant_info.issued_at
Beispiel #3
0
def verify_user(request):
    """csrf is not needed because it uses oidc token in the post
    """
    _name = sys._getframe().f_code.co_name
    debug_request(f'{_name}', request)

    token = request.POST.get('token')
    if not token:  # pragma: no cover
        return HttpResponse('Access forbidden: invalid token.', status=403)

    ec = oidcop_app.endpoint_context
    authn_method = ec.endpoint_context.authn_broker.get_method_by_id('user')

    kwargs = dict([(k, v) for k, v in request.POST.items()])
    user = authn_method.verify(**kwargs)
    if not user:
        return HttpResponse('Authentication failed', status=403)

    auth_args = authn_method.unpack_token(kwargs['token'])
    authz_request = AuthorizationRequest().from_urlencoded(auth_args['query'])

    # salt size can be customized in settings.OIDC_OP_AUTHN_SALT_SIZE
    salt_size = getattr(settings, 'OIDC_OP_AUTHN_SALT_SIZE', 4)
    authn_event = create_authn_event(uid=user.username,
                                     salt=base64.b64encode(
                                         os.urandom(salt_size)).decode(),
                                     authn_info=auth_args['authn_class_ref'],
                                     authn_time=auth_args['iat'])

    endpoint = oidcop_app.endpoint_context.endpoint['authorization']
    client_id = authz_request["client_id"]
    _token_usage_rules = endpoint.server_get(
        "endpoint_context").authn_broker.get_method_by_id('user')

    session_manager = ec.endpoint_context.session_manager
    _session_id = session_manager.create_session(
        authn_event=authn_event,
        auth_req=authz_request,
        user_id=user.username,
        client_id=client_id,
        token_usage_rules=_token_usage_rules)

    try:
        _args = endpoint.authz_part2(user=user.username,
                                     session_id=_session_id,
                                     request=authz_request,
                                     authn_event=authn_event)
    except ValueError as excp:
        msg = 'Something went wrong with your Session ... {}'.format(excp)
        return HttpResponse(msg, status=403)

    if isinstance(_args, ResponseMessage) and 'error' in _args:
        return HttpResponse(_args.to_json(), status=400)
    elif isinstance(_args.get('response_args'), AuthorizationErrorResponse):
        rargs = _args.get('response_args')
        logger.error(rargs)
        return HttpResponse(rargs.to_json(), status=400)

    response = do_response(request, endpoint, authz_request, **_args)
    return response
Beispiel #4
0
    def auth(self):
        # Start with an authentication request
        # The client ID appears in the request
        AUTH_REQ = AuthorizationRequest(
            client_id="client_1",
            redirect_uri="https://example.com/cb",
            scope=["openid", "mail", "address", "offline_access"],
            state="STATE",
            response_type="code",
        )

        # The authentication returns a user ID
        user_id = "diana"

        # User info is stored in the Session DB
        authn_event = create_authn_event(
            user_id,
            authn_info=INTERNETPROTOCOLPASSWORD,
            authn_time=time_sans_frac(),
        )

        user_info = UserSessionInfo(user_id=user_id)
        self.session_manager.set([user_id], user_info)

        # Now for client session information
        client_id = AUTH_REQ["client_id"]
        client_info = ClientSessionInfo(client_id=client_id)
        self.session_manager.set([user_id, client_id], client_info)

        # The user consent module produces a Grant instance

        grant = Grant(
            scope=AUTH_REQ["scope"],
            resources=[client_id],
            authorization_request=AUTH_REQ,
            authentication_event=authn_event,
        )

        # the grant is assigned to a session (user_id, client_id)
        self.session_manager.set([user_id, client_id, grant.id], grant)
        session_id = self.session_manager.encrypted_session_id(
            user_id, client_id, grant.id)

        # Constructing an authorization code is now done by

        code = grant.mint_token(
            session_id=session_id,
            endpoint_context=self.endpoint_context,
            token_class="authorization_code",
            token_handler=self.session_manager.
            token_handler["authorization_code"],
            expires_at=time_sans_frac() + 300,  # 5 minutes from now
        )

        # get user info
        user_info = self.session_manager.get_user_info(uid=user_id, )
        return grant.id, code
Beispiel #5
0
 def _create_session(self, auth_req, sub_type="public", sector_identifier=""):
     if sector_identifier:
         authz_req = auth_req.copy()
         authz_req["sector_identifier_uri"] = sector_identifier
     else:
         authz_req = auth_req
     client_id = authz_req["client_id"]
     ae = create_authn_event(self.user_id)
     return self.session_manager.create_session(
         ae, authz_req, self.user_id, client_id=client_id, sub_type=sub_type
     )
Beispiel #6
0
    def create_session(self, request, user_id, acr, time_stamp, authn_method):
        _context = self.server_get("endpoint_context")
        _mngr = _context.session_manager
        authn_event = create_authn_event(
            user_id,
            authn_info=acr,
            time_stamp=time_stamp,
        )
        _exp_in = authn_method.kwargs.get("expires_in")
        if _exp_in and "valid_until" in authn_event:
            authn_event["valid_until"] = utc_time_sans_frac() + _exp_in

        _token_usage_rules = _context.authz.usage_rules(request["client_id"])
        return _mngr.create_session(
            authn_event=authn_event,
            auth_req=request,
            user_id=user_id,
            client_id=request["client_id"],
            token_usage_rules=_token_usage_rules,
        )