Getting access token live time from program - wso2-identity-server

I am writing an Accesstoken Builder based on this
msf4j example. I do some filtering on roles and so on. I am using wso2is 5.8
I try to access the AccessTokenValidityPeriod set for the serviceprovider.
In my serviceprovider setup I have increased the "User Access Token Expiry Time", "Application Access Token Expiry Time" and "Id Token Expiry Time".
I can access the value of the token lifetime from the identity.xml file, but I want to lookup the specific settings for this serviceprovider.
My code looks like this
private long getLifetimeInMillis(OAuthAuthzReqMessageContext reqMessageContext, OAuthTokenReqMessageContext ctx) {
long lifetimeInMillis = -1;
if (reqMessageContext != null) {
log.debug("Get lifetime from OAuthAuthzReqMessageContext property");
lifetimeInMillis = reqMessageContext.getAccessTokenValidityPeriod();
/* always returns 0
... */
But this always returns 0.
I have debugged the OAuthAuthzReqMessageContext class, but only the Constructor is called an not the setter setAccessTokenValidityPeriod.
My pom.xml contains:
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
<version>5.12.387</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
<version>6.0.168</version>
<scope>provided</scope>
</dependency>

If your requirement is to get access token validity period use the following approach.
OAuth2AuthorizeReqDTO
authorizationReqDTO=reqMessageContext.getAuthorizationReqDTO();
SpOAuth2ExpiryTimeConfiguration spTimeConfigObj =
OAuth2Util.getSpTokenExpiryTimeConfig(authorizationReqDTO..getConsumerKey(),
IdentityTenantUtil.getTenantId(authorizationReqDTO.getUser().getTenantDomain()));
validityPeriodInMillis =
spTimeConfigObj.getUserAccessTokenExpiryTime();
Thanks

If you want to use a JWT access token in WSO2 Identity Server, you don't need to write any custom code in the latest releases. OAuth2/OIDC configs have this option to configure. See the bottom of the screenshot attached. So you don't need to have the JWTAccessTokenBuilder in the first place.

Related

How to specify the database in an ArangoDb AQL query?

If have multiple databases defined on a particular ArangoDB server, how do I specify the database I'd like an AQL query to run against?
Running the query through the REST endpoint that includes the db name (substituted into [DBNAME] below) ie:
/_db/[DBNAME]/_api/cursor
doesn't seem to work. The error message says 'unknown path /_db/[DBNAME]/_api/cursor'
Is this something I have to specify in the query itself?
Also: The query I'm trying to run is:
FOR col in COLLECTIONS() RETURN col.name
Fwiw, I haven't found a way to set the "current" database through the REST API. Also, I'm accessing the REST API from C++ using fuerte.
Tom Regner deserves primary credit here for prompting the enquiry that produced this answer. I am posting my findings here as an answer to help others who might run into this.
I don't know if this is a fuerte bug, shortcoming or just an api caveat that wasn't clear to me... BUT...
In order for the '/_db/[DBNAME/' prefix in an endpoint (eg full endpoint '/_db/[DBNAME/_api/cursor') to be registered and used in the header of a ::arangodb::fuerte::Request, it is NOT sufficient (as of arangodb 3.5.3 and the fuerte version available at the time of this answer) to simply call:
std::unique_ptr<fuerte::Request> request;
const char *endpoint = "/_db/[DBNAME/_api/cursor";
request = fuerte::createRequest(fuerte::RestVerb::Post,endpoint);
// and adding any arguments to the request using a VPackBuilder...
// in this case the query (omitted)
To have the database name included as part of such a request, you must additionally call the following:
request->header.parseArangoPath(endpoint);
Failure to do so seems to result in an error about an 'unknown path'.
Note 1: Simply setting the database member variable, ie
request->header.database = "[DBNAME]";
does not work.
Note 2: that operations without the leading '/_db/[DBNAME]/' prefix, seem to work fine using the 'current' database. (which at least for me, seems to be stuck at '_system' since as far as I can tell, there doesn't seem to be an endpoint to change this via the HTTP REST Api.)
The docs aren't very helpful right now, so just incase someone is looking for a more complete example, then please consider the following code.
EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
.authenticationType(AuthenticationType::Basic)
.user(?) // enter a user with access
.password(?) // enter the password
.connect(eventLoopService);
// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);
// enter the database name (ensure the user has access)
request->header.database = ?;
// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";
// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();
// add the payload to the request
request->addVPack(builder.slice());
// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));
// check the response code - it should be 201
unsigned int statusCode = response->statusCode();
// slice has the response data
VPackSlice slice = response->slices().front();
std::cout << slice.get("result").toJson() << std::endl;

How to find the size of a file uploaded via Dropwizard REST API

I am using Dropwizard 0.7.0 to build an API for file upload. Ran into trouble validating the uploaded file size limit. I want to check the size before writing the file to disk
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(#Context final HttpServletRequest request, #FormDataParam("file") FormDataBodyPart fileBodyPart) {
/*
* Check the request size
*/
request.getPart("file").getSize();
.........
}
it throws an error:
java.lang.IllegalStateException: No multipart config for servlet
at org.eclipse.jetty.server.Request.getParts(Request.java:2075) ~[jetty- server-9.0.7.v20131107.jar:9.0.7.v20131107]
at org.eclipse.jetty.server.Request.getPart(Request.java:2055) ~[jetty-server-9.0.7.v20131107.jar:9.0.7.v20131107]
EDIT ----------------------
#David
Upgraded to dropwizard 0.8.0 however ran into another error
com.sun.jersey.spi.inject.Errors: The following errors and warnings have been detected with resource and/or provider classes:
org.glassfish.jersey.media.multipart.file.FormDataBodyPart
org.glassfish.jersey.media.multipart.file.FileDataBodyPart
org.glassfish.jersey.media.multipart.FormDataContentDisposition
Using these dependencies
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-forms</artifactId>
<version>${dropwizard.version}</version>
</dependency>
and
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.23.2</version>
</dependency>
added
bootstrap.addBundle(new MultiPartBundle());
and this too (after first failure)
env.jersey().register(MultiPartFeature.class);
what am I missing here?
Being able to submit multipart data requires an additional dropwizard dependency. For 0.8 and higher the dependency is dropwizard-forms.
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-forms</artifactId>
<version>${dropwizard.version}</version>
</dependency>
http://www.dropwizard.io/0.8.0/docs/manual/forms.html
Example usage:
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("myFileName") InputStream file,
#FormDataParam("myFileName") FormDataContentDisposition fileMetaData
){
long fileSize = fileMetaData.getSize();
// etc
}
This is what I'm using. Perhaps upgrading is a solution for you.
If not, it is possible for dropwizard 0.7 but I haven't had to do it... From a quick google, it looks like you need the following dependency:
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.18.1</version>
</dependency>
... and add the following to your applications run method:
environment.jersey().register(MultiPartFeature.class);
Given the error "No multipart config for servlet" I'm assuming your upload doesn't work at all, without your size check?

Is there a way to read the entity as jax-rs client?

I just made a jax-rs service and I'm trying to convert the String I get from the service to entities. While with jax-rs everything is done automatically on the server side I assume there is a possibility to do it on the client side as well but I'm not finding it.
public class MyClient {
public static void main(String[] args) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8080/restapp/api/paints/1");
Response response = target.request().get();
Paint values = response.readEntity(Paint.class);
response.close();
}
}
this give an e:
Exception in thread "main" javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/json and type class client.Paint
(It works with String).
You need to add a JSON provider. For RESTeasy, you can see this link and select your version, and add the dependency.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy3.version}</version>
</dependency>
hi you can write ReastEasy or Jersy Client to get Json from your Service.
how to write client you can follow :http://entityclass.in/rest/jerseyClientGetXml.htm

InvokeHelper() throws Access is denied exception

Community, I have quite interesting and in the same time heavy problem.
I have VB .NET application + Service + C++ application. C++ application generates some data and makes callbacks using InvokeHelper() method:
InvokeHelper(0x60030000, DISPATCH_METHOD, VT_EMPTY, NULL, parms,
eventType, eventValue);
The first parameter is the dispid of method which should be called. Strange approach, but this is not my code and I can not change this way.
In service I have method marked by dispid attribute to get this callback from C++ application.
<DispId(&H60030000)>
Public Sub ServerEvent(ByVal vEventType As Integer, ByVal vEventValue As Object)
RaiseEvent ControlPanelStateChange(vEventType, vEventValue)
End Sub
This code works correctly if I logged on as admin. But if windows user has not administrator permissions, right after calling InvokeHelper() method the next exception occurs:
First-chance exception at 0x75B7C42D (KernelBase.dll) in application.exe: 0x80070005: Access is denied
Do you have any ideas? I have played with DCOM permissions, but result is the same.
Any help would be fantastic!
The solution of the problem is:
DCOMCNFG, right click on the My Computer and select properties -> COM Securities tab -> Access Permissions -> click Edit Defaults and add Network Service to it and give it Allow local access permission. Do the same for < Machine_name >\Users.
Then -> Launch and Activation Permissions, click Edit Defaults and add Network Service to it and give it Local launch and Local Activation permission. Do the same for < Machine_name >\Users.

Redirecting root context path or binding it to a servlet or mapping it with a welcome-file

I am using Jetty-9 in embedded mode and need only one web application. Consequently I would like the root URL to go to the homepage of that application, i.e. something like
http://localhost:4444/
should end up in a servlet. I start out with:
ServletContextHandler scContext =
new ServletContextHandler(ServletContextHandler.SESSIONS);
scContext.setContextPath("/");
None of the following worked, neither
scContext.addServlet(ListsServlet.class, "/");
nor
scContext.setWelcomeFiles(new String[]{"/lists})
where /lists is mapped to the ListsServlet servlet. All I get is a 403 (Forbidden).
I do not use the DefaultServlet, which seems to handle welcome files. But since the ServletContextHandler has setWelcomeFiles I expected it to contain the logic to use them.
Any ideas?
For the 403 Forbidden error, you have some security setup that is not allowing you to access the handlers/servlets.
Eliminate that security (for now), verify that the rest is working, then add security a bit later to lock down specifics.
If you want to see some the suggestions below at work, consider looking at the code example in the answer from another stackoverflow: How to correctly support html5 <video> sources with jetty.
Welcome files are appended to the incoming request path if there is nothing present at that location. For example requesting a directory and then a welcome-file of 'index.html' is appended to the request path.
While this would work ...
scContext.setWelcomeFiles(new String[]{"lists"})
// Add Default Servlet (must be named "default")
ServletHolder holderDefault = new ServletHolder("default",DefaultServlet.class);
holderDefault.setInitParameter("resourceBase",baseDir.getAbsolutePath());
holderDefault.setInitParameter("dirAllowed","true");
holderDefault.setInitParameter("welcomeServlets","true");
holderDefault.setInitParameter("redirectWelcome","true");
scContext.addServlet(holderDefault,"/");
It's likely not what you are aiming for, as you said the root path only.
The above would also make changes to requests like /foo/ to /foo/lists
Instead, it might make more sense to use a Rewrite rule + handler instead of the welcome-files approach.
RewriteHandler rewrite = new RewriteHandler();
rewrite.setHandler(scContext);
RewritePatternRule rootRule = new RewritePatternRule();
rootRule.setPattern("/");
rootRule.setReplacement("/list");
rootRule.setTerminating(true);
rewrite.addRule(rootRule);
server.setHandler(rewrite);
This RewritePatternRule simply changes any request path / to /list and then forwards that request to the wrapped ssContext (if you want to see the /list on the browser, change it to a RedirectPatternRule instead.