How to implement user login in Jersey API - rest

I am implementing RESTful API using javax.ws.rs. The response of the calls that I need to implement requires knowing which user is logged in currently. I tried making a separate call for the user login:
api.myapi.co.uk/authenticate?username=xxxx&password=xxxx
where I basically save the user information is a global variable
and then tried to make another call to retrieve information from the database based on the user that has been saved earlier but I find the value as null during the second call. What am I missing? Is my approach wrong? do you have any suggestions please?

Your code probably looks like this, right?
#Path("/")
public class MyResource{
private String username;
private String password;
#Path("authenticate")
public String authenticate(#QueryParam("username") username, #QueryParam("password") password) {
if(!username.equals("zainab") || !password.equals("letmein"))
return "Incorrect username or password";
this.username=username;
this.password=password;
return "Sucessfully authenticated";
}
#Path("secret")
public String secret() {
if(username == null || password == null)
return "Sorry, not authorized";
return "You are authorized: "+username;
}
}
If so, the problem is that JAX-RS creates a new Resource object for each request. A request to "/secret" then uses a new instance of MyResource, which has username and password as null.
Then, you might think, I'll just make it static! Then, your resource can't handle concurrent requests. What if Person A calls "/authenticate", then "/secret". Then Person B calls "/secret" without authenticating. He can then access "/secret" without authenticating!
Anyways, this violates the idea of RESTful services. The S in RESTful stands for "Stateless". This means that the server should store no state per client, and possibly give the user a token to pass with concurrent requests.
One possibility is to accept the username and password for every request to secret ("/secret?username=zainab&password=letmein"). Or you could implement token-based authentication, where the user calls "/authenticate" to get a token, and they pass that token on all later requests. Here is a link to help with that.
Also, note that username and password is usually not send in the URL as a query param, but instead in the Authorization HTTP header as such Authorization: base64encode("USERNAME:PASSWORD")

Related

How do I load a "user" in a micronaut backend when JWT is provided

I have a Micronaut microservice that handles authentication via JsonWebTokens (JWT) from this guide.
Now I'd like to extend this code. The users in my app have some extra attributes such as email, adress, teamId etc. I have all users in the database.
How do I know in the backend controller method which user corresponds to the JWT that is sent by the client?
The guide contains this example code for the Micronaut REST controller:
#Secured(SecurityRule.IS_AUTHENTICATED)
#Controller
public class HomeController {
#Produces(MediaType.TEXT_PLAIN)
#Get
public String index(Principal principal) {
return principal.getName();
}
}
I know that I can get the name of the principal, ie. the username from the HttpRequest. But how do I get my additional attributes?
(Maybe I misunderstand JWT a bit???)
Are these JWT "claims" ?
Do I need to load the corresponding user by username from my DB table?
How can I verify that the sent username is actually valid?
edit Describing my usecase in more detail:
Security requirements of my use case
Do not expose valid information to the client
Validate everything the client (a mobile app) sends via REST
Authentication Flow
default oauth2 flow with JWTs:
Precondition: User is already registerd. Username, hash(password) and furhter attributes (email, adress, teamId, ..) are known on the backend.
Client POSTs username and password to /login endpoint
Client receives JWT in return, signed with server secret
On every future request the client sends this JWT as bearer in the Http header.
Backend validates JWT <==== this is what I want to know how to do this in Micronaut.
Questions
How to validate that the JWT is valid?
How to and where in which Java class should I fetch additional information for that user (the additional attributes). What ID should I use to fetch this information. The "sub" or "name" from the decoded JWT?
How do I load a “user” in a micronaut backend when JWT is provided?
I am reading this as you plan to load some kind of User object your database and access it in the controller.
If this is the case you need to hook into the place where Authentication instance is created to read the "sub" (username) of the token and then load it from the database.
How to extend authentication attributes with more details ?
By default for JWT authentication is created using JwtAuthenticationFactory and going more concrete default implementation is DefaultJwtAuthenticationFactory. If you plan to load more claims this could be done by replacing it and creating extended JWTClaimsSet or your own implementation of Authentication interface.
How do I access jwt claims ?
You need to check SecurityService -> getAuthentication() ->getAttributes(), it returns a map of security attributes which represent your token serialised as a map.
How to validate that the JWT is valid?
There is a basic validation rules checking the token is not expired and properly signed, all the rest validations especially for custom claims and validating agains a third parties sources have to be done on your own.
If you plan to validate your custom claims, I have already open source a project in this scope, please have a look.
https://github.com/traycho/micronaut-security-attributes
How to extend existing token with extra claims during its issuing ?
It is required to create your own claims generator extending JWTClaimsSetGenerator
#Singleton
#Replaces(JWTClaimsSetGenerator)
class CustomJWTClaimsSetGenerator extends JWTClaimsSetGenerator {
CustomJWTClaimsSetGenerator(TokenConfiguration tokenConfiguration, #Nullable JwtIdGenerator jwtIdGenerator, #Nullable ClaimsAudienceProvider claimsAudienceProvider) {
super(tokenConfiguration, jwtIdGenerator, claimsAudienceProvider)
}
protected void populateWithUserDetails(JWTClaimsSet.Builder builder, UserDetails userDetails) {
super.populateWithUserDetails(builder, userDetails)
// You your custom claims here
builder.claim('email', userDetails.getAttributes().get("email"));
}
}
How do I access jwt claims ?
If you want to access them from the rest handler just add io.micronaut.security.authentication.Authentication as an additional parameter in the handling method. Example
#Get("/{fooId}")
#Secured(SecurityRule.IS_AUTHENTICATED)
public HttpResponse<Foo> getFoo(long fooId, Authentication authentication) {
...
}
I found a solution. The UserDetails.attributes are serialized into the JWT. And they can easily be set in my CustomAuthenticationProviderclass:
#Singleton
#Slf4j
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Publisher<AuthenticationResponse> authenticate(
#Nullable HttpRequest<?> httpRequest,
AuthenticationRequest<?, ?> authenticationRequest)
{
// ... autenticate the request here ...
// eg. via BasicAuth or Oauth 2.0 OneTimeToken
// then if valid:
return Flowable.create(emitter -> {
UserDetails userDetails = new UserDetails("sherlock", Collections.emptyList(), "sherlock#micronaut.example");
// These attributes will be serialized as custom claims in the JWT
Map attrs = CollectionUtils.mapOf("email", email, "teamId", teamId)
userDetails.setAttributes(attrs);
emitter.onNext(userDetails);
emitter.onComplete();
}, BackpressureStrategy.ERROR);
}
}
And some more pitfalls when validating the JWT in the backend
A JWT in Micronaut MUST contain a "sub" claim. The JWT spec does not require this, but Micronaut does. The value of the "sub" claim will become the username of the created UserDetails object.
If you want to load addition attributes into these UserDetails when the JWT is validated in the backend, then you can do this by implementing a TokenValidator. But (another pitfal) then you must set its ORDER to a value larger than micronaut's JwtTokenValidator. Your order must be > 0 otherwise your TokenValidator will not be called at all.

When using shiro to realize stateless application, do i need to login every request?

I use shiro and jwt and try to realize a stateless web application.
When i extend AuthorizingRealm, do i need to executeLogin every request?
Here is my executeLogin method:
public static boolean executeLogin(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authorization = httpServletRequest.getHeader("Authorization");
if (authorization == null || "".equals(authorization.trim())) {
throw RequestException.fail("未含授权标示,禁止访问");
}
JwtToken token = new JwtToken(authorization, null, null);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (DisabledAccountException e) {
if (e.getMessage().equals("verifyFail")) {
throw new RequestException(ResponseCode.NOT_SING_IN.code, "身份已过期,请重新登录", e);
}
throw new RequestException(ResponseCode.SIGN_IN_INPUT_FAIL.code, e.getMessage(), e);
} catch (Exception e) {
e.printStackTrace();
throw new RequestException(ResponseCode.SIGN_IN_FAIL, e);
}
// 如果没有抛出异常则代表登入成功,返回true
return true;
}
By Stateless means that each request does not depend from the previous, however this does not mean that Shiro does not use sessions.
When the user does a successful login Shiro attaches to the HTTPResponse some cookies. When the client sends the cookies to each further request, Shiro automatically extracts the Subject (associates the cookies with the user) so, in your code, you can immediately call SecurityUtils.getSubject().
A realm is the wrong approch here as it usually have by definition a 1-to-1 correlation with a data source. What you actually want to do is to controll access to your servers resources, verifying a JWT from a client. This can be done by a AccessControlFilter, reading the authorization header and verifing its claims in the filters isAccessAllowed method. The methods return value defines wheather access is allowed or not.
You don't need to login a subject at all since the AccessControlFilter decides wheather access is granted or denied, either forwarding the user to the requested resource or redirecting a 401 - Unauthorized response.
Yes, you should log in for each request. This will attach the subject to the current thread and allow you to use features: like use annotations for authz.
As you are using stateless call, you have to login each time and generate new subject and also load authorization details with appropriate realm.
The another option you could try is, put subject in cache (ehCache) once successful login and then on every request you can get subject from Cache and use for authorization. This will avoid login and authorization object population on every request. But you have to make sure to remove object from cache on logout event.
Similar thing has been already done by one user at:
https://github.com/jikechenhao/springmvc-shiro-react-redux-restful-example

Servicenow Rest API call to check if credentials are valid

I am calling ServiceNow Rest API for tables in my application. I allow the user to enter their servicenow instance credentials and domain url in my application.
I want to know if there is a Simple API call which I can make to ensure that the credentials entered are valid.
Currently I am making a call to get sys_user table and making the check.
This call seems to take more time. Is there a simpler REST URL which I can use here?
public static HttpConnectionResponse checkConnection(String host, String username, String password) {
String CHECK_URL = "/api/now/table/sys_user";
HttpConnectionResponse response = new HttpConnectionResponse();
String completeUrl = "https://"+host+CHECK_URL;
HashMap<String, String> requestHeaders = ConnectionUtils.getDefaultInputHeader();
Credential credential = ConnectionUtils.populateCredentials(username, password);
try{
response = HttpConnectorClient.getMethod(completeUrl, requestHeaders, credential);
}
catch(Exception e){
e.printStackTrace();
}
return response;
}
Why not just use any table or record that you've set to be accessible to any authenticated user, then make a REST API call with their credentials as the basic authentication credentials, to that resource? If you get the record rather than "access denied", the creds are valid. :-)
You could even make a simple UI page, or better yet, a Processor, just for that purpose.

How can the resource server identify the resource owner using token in oauth2?

The typical scenario I am looking into is:
User1 provides proper credentials to the front-end rest client (grant type: password) and the client gets the token in return.
The client sends the token and accesses the resources owned by User1.
In my scenario, once the client has the access token for user1, I want the client to have access limited to User1's resources only.
Consider that the client accesses the URI /users/1/books. The response will contain all the books associated with User1. The main problem is that if the client accesses the URL /users/2/books with User1's token, it gets the list of all the books for User2 which shouldn't be allowed.
How can I limit the scope to the user whose credentials were used to obtain the token?
How can I map the token to a specific user in my resource server?
I am using Spring/Java. But any general theory will also help.
After a lot of debugging, I got the answer.
Spring security 1.4
Token store: InMemoryTokenStore()
In ResourceServerConfiguration, configure HttpSecurity.
#Override
public void configure(final HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().
// antMatchers("/oauth/token").permitAll().
antMatchers("/api/users/{userId}").access("#webSecurity.checkUserId(authentication,#userId)")
.anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
// #formatter:on
}
Create a class WebSecurity and provide the implementation.
public class WebSecurity {
public boolean checkUserId(Authentication auth, int id) {
return ((UmUser)auth.getPrincipal()).getId() == id;
}
}
Resources:
http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html#el-access-web-path-variables
http://www.baeldung.com/get-user-in-spring-security
I had to debug a lot as I was using JwtTokenStore. This returned the Principal as a String and not the instance of UserDetails as I was expecting.
Once I switched to InMemoryTokenStore, I got the expected results. This was not a problem for me as I had the choice, but I would still like to know how to achieve it with the JWT.

How to deal with anonymous login attempts when you allow both anonymous access and logged in users?

I have a framework that allows anonymous access as well as named user accounts. I'm exposing an OData resource on a certain URL. When configured as such, anonymous users can see parts of the resource and logged in users (through basic authentication) can see more.
The problem I'm facing is that some OData clients (like Excel) will initially attempt to access the OData resource anonymously even when you do provide credentials. Only when this fails, they will use the provided credentials. My understanding is that this is because there are many ways to log in and some clients just always try the most basic option first. But this prevents them from ever actually seeing more data, because they never use the provided credentials and also never get the authentication challenge when the resource allows anonymous access.
Is there a way to solve this issue, allowing both anonymous access AND properly sending an authentication challenge when possible? Is there maybe some header that clients will send when they do have credentials but just aren't supplying them initially?
Some (scala) code to make this a bit more tangible:
val (username, password) = getAuthInfo(request)
if (username != null && password != null) {
val regularSession = integration.core.login(username, password)
logger.debug(s"Login OK: User '$username' (Number of concurrent sessions: ${integration.core.getNumberConcurrentSessions}).")
(IMxRuntimeResponse.OK, null, regularSession)
} else if (integration.configuration.getEnableGuestLogin) {
val guestSession = integration.core.initializeGuestSession
logger.debug(s"Anonymous user '${guestSession.getUser.getName}' created " +
"(Number of concurrent sessions: ${integration.core.getNumberConcurrentSessions}).")
(IMxRuntimeResponse.OK, null, guestSession)
} else {
val responseMessage = "No basic authentication in header."
logger.warn(s"Login failed: $responseMessage")
(IMxRuntimeResponse.UNAUTHORIZED, responseMessage, null)
}
Somewhere else outside the surrounding try/catch:
if (httpStatusCode == IMxRuntimeResponse.UNAUTHORIZED)
response.addHeader("WWW-Authenticate", "Basic")
As you can see the challenge is never sent when anonymous access is allowed.
Edit: we investigated and there does not seem to be anything special in the headers of this request that would indicate this is an initial attempt that will result in another request when an authentication challenge is sent, rather than just another anonymous login attempt. We are at a loss here now on how to proceed.