Endpoint with no authorization - jhipster

Is there any possibility of generating an endpoint with jhipster with no authorization? Every endpoint requires authorization header by default (as far as I know), but I would like to allow usage of one of the endpoints without authorization header.

You can do do by going to
your-app/config/SecurityConfiguration.java
on this method
#Override
public void configure(HttpSecurity http) throws Exception {
...
authorizeRequests
add this line
.antMatchers("/api/some-unsafe-url").permitAll()

Related

Identity Server 4 asp.net 2.1 - IProfileService or alternative

I will buy anyone a beer who can solve my problem!
As a piece of work I need to update our Identity Server to use an implicit login flow, it was currently using Bearer Token access only. As a part of our architecture we are using Multi-tenancy.
For security reaosns we need to check the tenant header to verify that the user is not impersonating another tenant. To do this from a client perspective we use a custom IProfileService. This gets triggered in the middleware of Identity Server, meaning all is good!
However if I was a user and I wanted to use some form of functionality on Identity Server itself and not an actual client of it, then IProfileService will not be triggered. An example of this would be to revoke access to clients, or even log out.
The GetProfileDataAsync Method on IProfileService is Invoked when the client request additional claims for the user.
germansak on Github Issue here had a similar issue and it was never quite answered (https://github.com/IdentityServer/IdentityServer4/issues/1643)
Leading to my question, how has anyone been able to verify a Tenant on Identity Server itself when they are not going through a Client, but instead Identity Server. If I can't trigger IProfileService I feel as if I'm beat!
Both logout and grants functionality is not part of the identity server 4 core package and they are simply implemented as ASP.NET Core razor views outside of the oauth2 flows.
There are few ways to validate headers therefore, I guess the easiest in my opinion would be to add another middleware.
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<TenantHeaderValidationMiddleware>();
...Your other config
}
public class TenantHeaderValidationMiddleware
{
private readonly RequestDelegate _next;
public RequestCultureMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
string tenantId = Request.Headers["YourTenantIdHeader"];
//do the checking
...Validation logic
//pass request further if correct
await _next(context);
}
}

Validate Access token in service to service authentication using azure oauth2

I want to enable service to service authentication in my services using spring boot and azure oauth2.I have generated access token using
https://login.microsoftonline.com//oauth2/token (POST)
I want to validate that whenever my service is hit with this access token , it should the request or throw 403.It is always throwing 403.
Hitting after putting header : Authorization -> Bearer access_token
#EnableWebSecurity
#Configuration
public class WebAuthentication extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/subordinate").permitAll();
http.authorizeRequests().antMatchers("/api/**").authenticated();
}
}
What should be added to validate service based authentication token.(No user is involved in generating token)

authorization code from Azure AD OAuth2AuthorizationResponse

I have got the Springboot Active Directory example up and running as specified here:
https://github.com/Microsoft/azure-spring-boot/tree/master/azure-spring-boot-samples/azure-active-directory-spring-boot-backend-sample
I can log in with my Azure AD credentials, using a Client ID that I created and granted 'Windows Azure Active Directory' permissions on.
Next step is I'd like to get the logged-in user's profile picture, so I need to get the Authorization Code from the OAuth2AuthorizationResponse
It's not clear to me how to access this data. It's not available in the returned OAuth2User object
I tried setting up a HandlerInterceptor on /login/oauth2/code/azure so I can intercept the Response, but this never gets hit (?)
I also tried adding a custom filter:
http.addFilterAfter(
new CustomFilter(), BasicAuthenticationFilter.class)
but this never gets hit for the /login/oauth2/code/azure URI
I was able to intercept the Authentication response by overriding SavedRequestAwareAuthenticationSuccessHandler and adding it to my security config:
http....
.and().oauth2Login().successHandler(authCodeCachingSuccessHandler)
where I cache the code and pass to superclass to handle:
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
Map<String, String[]> parameterMap = request.getParameterMap();
String[] s = parameterMap.get("code");
tokenCache.setAuthCode( (DefaultOidcUser) authentication.getPrincipal(), s[0] );
super.onAuthenticationSuccess(request, response, authentication);
}
I doubt this is 'best practice' but it does work, and I've yet to find a more elegant way

How to implement Authorization in ASP.NET Web API using Windows Azure

I have sample ASP.NET Web API with get method, I have prefixed a [Authorize] attribute on top of the method. Can I please know how should I call this method from browser or fiddler? Also, I am hosting these API's on Windows Azure
public class ValuesController : ApiController
{
// GET api/values
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Depending on the type of authorization you are using there might be different ways. But if you are using default routing you could call your method at the following url:
/api/values
You might of course need to pass additional headers depending on the authorization mechanism you choose. The [Authorize] attribute doesn't do anything unless you have configured some authorization. You may take a look at the following article for an example of how you could use tokens to authenticate your users.

Where should I plugin the Authorization in Asp.net WebAPI?

As I see I have 3 possible places to plug my stuff in the pipeline
1) AuthorizationFilters
2) Action Filters
3) DelegatingHandler
The most obvious one is AuthorizationFilters , where I can decorate my actions/ controllers with my custom authorization attribute . say .. MyCustomAuthorizationAttribute .
Since HTTP message handlers are in the first stage in the processing pipeline. Does it make any sense to put it in there ?
Authorization for me right now simply means checking a token in the header which is given to the client after authentication.
Update July 2014
My original answer covered WebApi 1. with WebApi 2 there were some changes i.e. there is now an IAuthenticationFilter meaning you can move authentication logic out of the DelegatingHandler which is a little more elegant.
There is a Nuget project here that offers an implementation of IAuthenticationFilter and also explains some background to its introduction.
OWIN middleware is now perhaps the best place to implement your authentication logic - there is an example of Certificate Authentication here and Basic Authentication OWIN Middleware here in this blog post the former example is the preferred one as it demonstrates the use of the base AuthenticationHandler class.
The advice on AuthorizationFilters remains largely unchanged.
End Update
Typically...
Use DelegatingHandler to carry out Authentication... i.e. who someone is. Use this to set the Principle of the Thread and User context, add claims etc. You can place authorisation logic here too but on a fairly global scale. I would personally always use AuthorizationFilters for authorisation.
Use AuthorizationFilters to restrict controllers and actions to specific people. These are used when you can extrapolate their permission with the information in claims, principal, url or the http request parameters. The default authorisation filter can be used to restrict access to anonymous users or by roles (if set in something like a delegating handler) - obviously you can implement your own AuthorizationFilters too if you need it.
Occasionally use ActionFilters when you need to make the decision over authorisation using the message content e.g. you need access to a property on the entity to decide whether they have access (obviously be careful with this(!)).
Note:
The AuthorizationFilters are called before the content of the body is read therefore they do not have access to the message body to make authorization decisions this is why the ActionFilters specifically the OnActionExecuting is used to occasional raise authentication errors.
So
In your scenario I would put a simple DelegatingHandler to take your header and set the principal.
public class CustomAuthenticationMessageHandler : DelegatingHandler
{
public CustomAuthenticationMessageHandler ()
{
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
Authenticate(request);
return base.SendAsync(request, cancellationToken);
}
protected virtual void Authenticate(HttpRequestMessage request)
{
var authorisationHeader = request.Headers.Authorization;
if (authorisationHeader == null)
{
return;
}
//Ensure you are happy with the header contents then
{
var principal = new GenericPrincipal(//new Identity , //Roles);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
}
}
Then use AuthorizationFilters to restrict access:
[Authorize]
public string Get()
{
}
[Authorize(Roles = "Admin")]
public string GetAdminOnly()
{
}
To register the global Authentication
config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
This will mean that in every request the principal will be set to either null or a valid identity. It won't handle authorisation i.e. wont deny access to any controllers or actions.
To start protecting resources
Either target protected controllers and actions with the standard or custom [Authorize] attributes. Or register globally:
config.Filters.Add(new AuthorizeAttribute());
And only white list the controllers and actions you want unsecured using the [AllowAnonymous] attribute.
If you only want authentication on some routes
Then you can modify your DelegatingHandler a little to set the InnerHandler to route to the correct controller e.g.
public CustomAuthenticationMessageHandler(HttpConfiguration configuration)
{
InnerHandler = new HttpRoutingDispatcher(configuration);
}
And then you can specify this handler on your routes like so:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "myurl",
defaults: new {},
constraints: new {},
handler: new CustomAuthenticationHandler(config)
);

Resources