mvc6 unauthorized results in redirect instead - redirect

I have been trying to prevent the redirect when I return an NotAuthorized IActionResult from a Controller, but regardless of my attempts, NotAuthorized gets translated to a Redirect.
I have tried what is mentioned here (same issue, using older beta framework, I use 1.0.0-rc1-final). I do not have the Notifications namespace (has been removed in rc1-final).
This is my Login Controller:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Ok(model);
}
if (result.IsLockedOut)
{
return new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
}
else
{
return HttpUnauthorized();
}
}
return HttpUnauthorized();
}
In Startup.cs I have tried variations over this:
services.Configure<CookieAuthenticationOptions>(o =>
{
o.LoginPath = PathString.Empty;
o.ReturnUrlParameter = PathString.Empty;
o.AutomaticChallenge = false;
});
Everytime a login fails (please ignore that the password is returned on Ok) and should result in an empty 401 page, I get a redirection to /Account/Login instead. What is the trick here?

The solution is not to configure CookieAuthenticationOptions directly, but do it via IdentityOptions like this:
services.Configure<IdentityOptions>(o =>
{
o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if (ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
return Task.FromResult<object>(null);
}
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
};
});

Taken from here ( Shawn Wildermuth --> ASP.NET 5 Identity and REST APIs --> Comment of "Mehdi Hanafi") and tested the API with Postman
config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api") &&
ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.FromResult<object>(null);
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
}
};

from Identity 2.0,
you'd need to add:
using Microsoft.AspNetCore.Authentication.Cookies;
and in ConfigureServices:
services.ConfigureApplicationCookie(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = (x =>
{
if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
x.Response.StatusCode = 401;
return Task.CompletedTask;
}),
OnRedirectToAccessDenied = (x =>
{
if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
x.Response.StatusCode = 403;
return Task.CompletedTask;
})
};
});
the segments check should of course be adjusted to your routes.

If you have some pages for which the redirect is desired and other URLs that should not have a redirect, see this question for a solution that uses the default redirect logic only for non-API URLs:
Suppress redirect on API URLs in ASP.NET Core

Related

OpenIdConnect Authentication Cookie not being deleted on signing out

I'm trying to implement OpenIdConnect as my authentication provider, using .NET6. I have the sign-in part working properly, however, on sign-out, the authentication cookie is not being deleted.
I've seen plenty of other threads referencing similar problems (this, for example provides a pretty good summary of several of these), but none of the approaches seem to work.
Broadly speaking, my authentication code is configured as follows:
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = AuthenticateScheme;
options.DefaultSignOutScheme = AuthenticateScheme;
options.DefaultChallengeScheme = ChallengeScheme;
})
.AddCookie(AuthenticateScheme, options =>
{
//trying to avoid having to add this!
//options.Events.OnSigningOut = async ctx =>
//{
// await Task.Run(() => ctx.HttpContext.Response.Cookies.Delete(CookieName));
//};
})
.AddOpenIdConnect(ChallengeScheme, options =>
{
options.SignInScheme = AuthenticateScheme;
options.SignOutScheme = AuthenticateScheme;
options.ResponseType = OpenIdConnectResponseType.Code;
options.CallbackPath = CallbackPath;
options.UsePkce = true;
options.Authority = Authority;
options.ClientId = ClientId;
options.ClientSecret = ClientSecret;
options.Scope.Clear();
options.Scope.Add(OpenIdConnectScope.OpenId);
options.Scope.Add(OpenIdConnectScope.OfflineAccess);
options.Scope.Add(OpenIdConnectScope.Email);
options.Scope.Add(OpenIdConnectScope.OpenIdProfile);
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = "roles",
NameClaimType = "preferred_username",
ValidateIssuer = false
};
options.Events.OnRedirectToIdentityProvider = ctx =>
{
// Prevent redirect loop
if (ctx.Response.StatusCode == 401)
{
ctx.HandleResponse();
}
return Task.CompletedTask;
};
options.Events.OnAuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.BodyWriter.WriteAsync(Encoding.ASCII.GetBytes(context.Exception.Message));
return Task.CompletedTask;
};
});
And over on my Startup.cs, I have the following code within the Configure method:
app.Map("/Logout", map =>
{
map.Run(async appBuilder =>
{
// tried this, didn't work
//await appBuilder.SignOutAsync("MyAuthCookie", new AuthenticationProperties { RedirectUri = "/" });
// tried this, didn't work
//await appBuilder.SignOutAsync();
});
});
app.UseNotFoundHandler();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGetaCategories();
app.UseGetaCategoriesFind();
app.UseAnonymousId();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "Default", pattern: "{controller}/{action}/{id?}");
endpoints.MapControllers();
endpoints.MapRazorPages();
endpoints.MapContent();
});
Any suggestions would be greatly appreciated. For now, the only way I've been able to get this to work is to explicitly delete the cookie within the OnSigningOut event, but this doesn't feel like the right approach.
A more complete logout should look something like this:
/// <summary>
/// Do the logout
/// </summary>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Logout()
{
await HttpContext.SignOutAsync(AuthenticateScheme);
await HttpContext.SignOutAsync(ChallengeScheme);
//Important, this method should never return anything.
}
You might need to tweak the schema names if you don't use the default ones.
In the AddAuthentication method, I would se these settings, you want cookie for everything except the challenge.
services.AddAuthentication(options =>
{
options.DefaultScheme = AuthenticateScheme;
options.DefaultChallengeScheme = ChallengeScheme;
})

Refreshing access token with multiple requests

Im struggling with getting axios interceptors to work.
When my token expires, i need it to refresh the access token and retry the original request once the token is refreshed.
I have this part working.
The problem is if i have concurrent api calls it will only retry the first request when the token was first invalid.
Here is my interceptor code:
export default function execute() {
let isRefreshing = false
// Request
axios.interceptors.request.use(
config => {
var token = Storage.getAccessToken() //localStorage.getItem("token");
if (token) {
console.log('Bearer ' + token)
config.headers['Authorization'] = 'Bearer ' + token
}
return config
},
error => {
return Promise.reject(error)
}
)
// Response
axios.interceptors.response.use(
response => {
return response
},
error => {
const originalRequest = error.config
// token expired
if (error.response.status === 401) {
console.log('401 Error need to reresh')
originalRequest._retry = true
let tokenModel = {
accessToken: Storage.getAccessToken(),
client: 'Web',
refreshToken: Storage.getRefreshToken()
}
//Storage.destroyTokens();
var refreshPath = Actions.REFRESH
if (!isRefreshing) {
isRefreshing = true
return store
.dispatch(refreshPath, { tokenModel })
.then(response => {
isRefreshing = false
console.log(response)
return axios(originalRequest)
})
.catch(error => {
isRefreshing = false
console.log(error)
// Logout
})
} else {
console.log('XXXXX')
console.log('SOME PROBLEM HERE') // <------------------
console.log('XXXXX')
}
} else {
store.commit(Mutations.SET_ERROR, error.response.data.error)
}
return Promise.reject(error)
}
)
}
I'm not sure what i need in the else block highlighted above.
EDIT:
When I do
return axios(originalRequest)
in the else block it works, however im not happy with the behaviours. It basically retries all the requests again and again until the token is refreshed.
I would rather it just retried once after the token had been refreshed
Any ideas
Thanks
You can just have additional interceptor which can refresh token and execute your pending requests.
In this, countDownLatch class can help.
Here is sample Interceptor code,
class AutoRefreshTokenRequestInterceptorSample() : Interceptor {
companion object {
var countDownLatch = CountDownLatch(0)
var previousAuthToken = ""
const val SKIP_AUTH_TOKEN = "SkipAccessTokenHeader"
const val AUTHORIZATION_HEADER = "AUTHORIZATION_HEADER_KEY"
}
#Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response? {
val request = chain.request()
if (shouldExecuteRequest(request)) {
// Execute Request
val response = chain.proceed(request)
if (!response.isSuccessful) {
// Failed Case
val errorBody = response.peekBody(java.lang.Long.MAX_VALUE).string()
val error = parseErrorModel(errorBody)
// Gives Signal to HOLD the Request Queue
countDownLatch = CountDownLatch(1)
handleError(error!!)
// After updating token values, execute same request with updated values.
val updatedRequest = getUpdatedRequest(request)
// Gives Signal to RELEASE Request Queue
countDownLatch.countDown()
//Execute updated request
return chain.proceed(updatedRequest)
} else {
// success case
return response
}
}
// Change updated token values in pending request objects and execute them!
// If Auth header exists, and skip header not found then hold the request
if (shouldHoldRequest(request)) {
try {
// Make this request to WAIT till countdown latch has been set to zero.
countDownLatch.await()
} catch (e: Exception) {
e.printStackTrace()
}
// Once token is Updated, then update values in request model.
if (previousAuthToken.isNotEmpty() && previousAuthToken != "newAccessToken") {
val updatedRequest = getUpdatedRequest(request)
return chain.proceed(updatedRequest)
}
}
return chain.proceed(request)
}
private fun handleError(error: ErrorDto) {
// update your token as per your error code logic
//Here it will make new API call to update tokens and store it in your local preference.
}
/***
* returns Request object with updated token values.
*/
private fun getUpdatedRequest(request: Request): Request {
var updateAuthReqBuilder: Request.Builder = request.newBuilder()
var url = request.url().toString()
if (url.contains(previousAuthToken.trim()) && previousAuthToken.trim().isNotEmpty()) {
url = url.replace(previousAuthToken, "newAccessToken")
}
updateAuthReqBuilder = updateAuthReqBuilder.url(url)
// change headers if needed
return updateAuthReqBuilder.build()
}
private fun shouldExecuteRequest(request: Request) =
shouldHoldRequest(request) && isSharedHoldSignalDisabled()
/**
* If count down latch has any value then it is reported by previous request's error signal to hold the whole pending chain.
*/
private fun isSharedHoldSignalDisabled() = countDownLatch.count == 0L
private fun shouldHoldRequest(request: Request) = !hasSkipFlag(request) && hasAuthorizationValues(request)
private fun hasAuthorizationValues(request: Request) = isHeaderExist(request, AUTHORIZATION_HEADER)
private fun hasSkipFlag(request: Request) = isHeaderExist(request, SKIP_AUTH_TOKEN)
private fun isHeaderExist(request: Request, headerName: String): Boolean {
return request.header(headerName) != null
}
private fun parseErrorModel(errorBody: String): Error? {
val parser = JsonParser()
// Change this logic according to your requirement.
val jsonObject = parser.parse(errorBody).asJsonObject
if (jsonObject.has("Error") && jsonObject.get("Error") != null) {
val errorJsonObj = jsonObject.get("Error").asJsonObject
return decodeErrorModel(errorJsonObj)
}
return null
}
private fun decodeErrorModel(jsonObject: JsonObject): Error {
val error = Error()
// decode your error object here
return error
}
}
This is how I do:
let isRefreshing = false;
let failedQueue = [];
const processQueue = (error, token = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token);
}
});
failedQueue = [];
};
axios.interceptors.response.use(
response => response,
error => {
const originalRequest = error.config;
if (error.response.status === 400) {
// If response is 400, logout
store.dispatch(logout());
}
// If 401 and I'm not processing a queue
if (error.response.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
// If I'm refreshing the token I send request to a queue
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
})
.then(() => {
originalRequest.headers.Authorization = getAuth();
return axios(originalRequest);
})
.catch(err => err);
}
// If header of the request has changed, it means I've refreshed the token
if (originalRequest.headers.Authorization !== getAuth()) {
originalRequest.headers.Authorization = getAuth();
return Promise.resolve(axios(originalRequest));
}
originalRequest._retry = true; // mark request a retry
isRefreshing = true; // set the refreshing var to true
// If none of the above, refresh the token and process the queue
return new Promise((resolve, reject) => {
// console.log('REFRESH');
refreshAccessToken() // The method that refreshes my token
.then(({ data }) => {
updateToken(data); // The method that sets my token to localstorage/Redux/whatever
processQueue(null, data.token); // Resolve queued
resolve(axios(originalRequest)); // Resolve current
})
.catch(err => {
processQueue(err, null);
reject(err);
})
.then(() => {
isRefreshing = false;
});
});
}
return Promise.reject(error);
},
);
I don't know what is the schema of your token (after decrypted) but one of the attributes which is a good practice to keep is the exp "expiration_date".
Said so, having the expiration date you can know when you should refresh your token.
Without understanding your architecture is hard to inform the right solution. But let's say you are doing everything manually, usually onIdle/onActive is when we check if the user session is still ok, so at this time you could use the token info to know if you should refresh its value.
It is important to understand this process because the token should be refreshed only if the user is constantly active and it is about to expire (like 2min before).
Please refer to angular version of the code for which i was facing the same problem and after changing many approaches this was my final code which is working at its best.
Re Initaite the last failed request after refresh token is provided

In AspBoilerPlate - Unauthorized error when calling from Angular when Windows Authentication is On

Have already raised this before and thought I have addressed it as per what suggested on THIS and THIS but seems not!
I am using ABP template (Angular and ASP .NET CORE Application) on Full .Net Framework. I simply want to use Windows Authentication to Authenticate user.
I added [Authorize] to the Authenticate in the TokenAuthController and have finally got the HttpContext.User.Identity.Name populated but only when I call the Authenticate from the Swagger (http://localhost:21021/swagger). But I am getting Unauthorized error when calling the method from Angular (login.service.ts):
POST http://localhost:21021/api/TokenAuth/Authenticate 401 (Unauthorized)
Here is the steps I have taken so far:
Changed launchSetting.json:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:21021/",
"sslPort": 0
}
},
Added ExternalAuthenticationSource:
public class WindowsAuthSource : DefaultExternalAuthenticationSource<Tenant, User>, ITransientDependency
{
public override string Name
{
get { return "Windows Authentication"; }
}
public override Task<bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, Tenant tenant)
{
return Task.FromResult(true);
}
}
Added it to CoreModule:
Configuration.Modules.Zero().UserManagement.ExternalAuthenticationSources.Add<WindowsAuthSource>();
4.Adjust AuthConfigurer:
services.AddAuthentication(opt => {
opt.DefaultScheme = IISDefaults.AuthenticationScheme;
opt.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;
});
Adjust StartUp.cs:
services.Configure<IISOptions>(iis =>
{
iis.AuthenticationDisplayName = "WINDOWS";
iis.AutomaticAuthentication = true;
});
Changed Authenticate method in the TokenAuthController:
public async Task<AuthenticateResultModel> Authenticate([FromBody]
AuthenticateModel model)
{
//var username = WindowsIdentity.GetCurrent().Name.Split('\\').Last();
var username = HttpContext.User.Identity.Name;
model.UserNameOrEmailAddress = username;
var loginResult = await GetLoginResultAsync(
model.UserNameOrEmailAddress,
model.Password,
null
);
var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new AuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
UserId = loginResult.User.Id
};
}
Sending dummy username and password from login.service.ts:
authenticate(finallyCallback?: () => void): void {
finallyCallback = finallyCallback || (() => { });
//Dummy data
this.authenticateModel.userNameOrEmailAddress = "DummyUsername";
this.authenticateModel.password = "DummyPassword";
this._tokenAuthService
.authenticate(this.authenticateModel)
.finally(finallyCallback)
.subscribe((result: AuthenticateResultModel) => {
this.processAuthenticateResult(result);
});
}

Ionic2 - http get is not working

I have written a authentication service to authenticate user name and password in a Login Page. The code below is the service.
public login(credentials) {
if (credentials.username === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
'&password=' + credentials.password ;
return Observable.create(observer => {
this.http.get(apiURL).map(res => res.json()).subscribe(data => {
if (data.success === 'true')
{
this.currentUser.name = data.data.user_name;
this.currentUser.email = data.data.user_email;
observer.next(true);
observer.complete();
} else {
observer.next(false);
observer.complete();
}
});
});
}
}
When the user name and password is submitted, the URL is correctly called with the right parameters.
The http call takes very long time to complete. Also, no response is returned.
It takes only two or three seconds to get the response when I call the URL with the same parameters in the browser.
Any idea on how to fix this?
You don't need to create a new Observable you can refactor like this.
public login(credentials) : Observable<boolean> {
if (credentials.username === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
'&password=' + credentials.password ;
return this.http.get(apiURL).map(res => res.json())
.map(data =>
{
if(data.success){
this.currentUser.name = data.data.user_name;
this.currentUser.email = data.data.user_email;
return true;
}else{
return false;
}
});
}
}

Drupal JSON POST from PhoneGap

I am trying to send a POST request to Drupal's Services module & JSON_Server module, however I am getting
{ "#error": true, "#data": "Invalid method " }
Since PhoneGap runs html files from locally on the phone, should i need to worry about JSONP. The issue I have with that is that I must POST data, and JSONP only allows for GET. Any ideas would be helpful. Thanks!
//SEND REQUEST AND CALLBACK FUNCTION
var req;
DrupalService.prototype.request = function(dataObject, callback){
req = false;
var url = DRUPAL_JSON_URL;
var params = "data="+dataObject;
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
console.log(">> "+req.responseText);
}
}
req.open("POST", url, false);
req.send(params);
}
}
So i figured it out, It had to do with conflicting content types
make sure you set it as
Content-Type = application/x-www-form-urlencoded;
var DRUPAL_JSON_URL = "http://myDrupalsSite.com/services/json";
var req;
DrupalService.prototype.request = function(dataObject, callback){
var url = DRUPAL_JSON_URL;
req = false;
var params = "method=system.connect";
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
alert("test " + req.responseText)
console.log("RESPONSE "+req.responseText);
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(params);
}
}