Windows authentication + angular. Prevent login prompt - javascript

I'm tryng to authenticate my angular app with Windows auth. I make a call to an authorized api and wait for result to check if user is a windows user.
If user is authorized everything is ok, api return 200 status code.
If user is unauthorized a browser default login popup be shown. I want to intercept 401 response and show a custom error dialog, not the browser popup
There is a way to prevent login popup to be shown?
Thanks.
Here an example of my request:
var ret = this.http.get(this.baseUrl + this._hello, {headers: {'X-Requested-With':'XMLHttpRequest'}, withCredentials:true})
.map(this.extractDataa)
.catch(this.handleError);

If you have an authenticated (any variable name will work) variable in the .ts file of the component that contains the log-in pop-up, you can use that variable in the .html of the component.
<ng-container *ngIf="!authenticated">
<app-login>/* log-in component */<app-login>
<ng-container>
This will only render the content in the ng-container if authenticated is false

Related

how can I redirect a url to another url?

MY application url is : http://219.41.192.244:8080/KanaApp/login - it will take user to login page
Login is the first page then only user can access the application.
But if user put this url - http://219.41.192.244:8080/KanaApp , it's redirecting to http://219.41.192.244:8080/KanaApp/#/home and taking user to the home page without login. How can I prevent this and make the login page mandatory?
whenever user put this url http://219.41.192.244:8080/KanaApp, I want redirect to http://219.41.192.244:8080/KanaApp/login url, can someone help me here please.
Spring boot application:
I have set the context path here
server.contextPath=/KanaApp
and in front end angular
SecurityConfig class:
.antMatchers("/static/**").permitAll()
.antMatchers("/assets/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/forgotPassword").permitAll()
.antMatchers("/setForgotPassword").permitAll()
.and()
.formLogin()
.successHandler(handler)
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/login").permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true).permitAll()
.and()
.csrf().disable();
I think what you are missing is a proper security configuration.
If you want your user to be connected, then you must force your user to be. Meaning that you must allow requests only to authenticated user.
You will find a lot of guide on how doing it spring example here.
What you must do is register a class extending WebSecurityConfigurerAdapter, and define which part of your application are secured.
For example:
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
Meaning all uris in /public/... would be allowed for everyone, so you won't have to login to go there, and any others needs to be logged to go there.
As you have a login page, a basic way to force users to go there is to implement spring form login (specified in more depth in the link before). This is the part doing the job
.formLogin()
.loginPage("/login")
.permitAll()
Declaring spring security form login, all request that must be authenticated will be redirected to the page specified here. You can of course customize this page as you like (an example from spring documentation).

Manually Login by Facebook in Angular6 and Laravel

I'm developing an application which I'm writing in Angular 6 framework.
Currently, I would like to add user login by social media like: Facebook, Google, Twitter, Github, LinkedIn.
I have a four buttons for these actions in my SocialLoginComponent's template:
Now I'm trying to implement user login by facebook after clicking on CONNECT WITH FACEBOOK button which has an click angular action:
<button (click) = "loginWithFacebook()" class="social-button" id="facebook-connect"> <span>Connect with Facebook</span></button>
Implementation of function loginWithFacebook looks like:
loginWithFacebook() {
this.auth.loginByFacebook(this.apiKey, this.redirectUri).subscribe({
next: (v) => console.log(v)
});
}
Here auth is of course service injected by constructor:
constructor(private auth: AuthService) {
}
Below I show implementation method loginByFacebook method in my AuthService:
loginByFacebook(appId, redirectUri) {
const facebookParams = new HttpParams()
.set('client_id', appId)
.set('redirect_uri', redirectUri)
.set('response_type', 'token');
return this.http.get(this.facebookUrl, {params : facebookParams});
});
where facebookUrl is the AuthService property:
private facebookUrl = 'https://www.facebook.com/v3.1/dialog/oauth';
I'm setting up here of course parameters based on My Facebook App.
I'm trying to invoke that url by get method in order to obtain a facebook login dialog based on description from tutorial: manualyBuildALoginFlow. I wouldn't like to use JavaScript SDK in my solution.
In current state when I'm clicking on the faecebook button, there is response like below:
I would like to obtain modal dialog with confirmation like below:
In my Get request I add parameter response_type = token in order to obtain Social token. On the below diagram I show what flow I'm trying to achieve:
On above diagram my server is laravel framework which currently handle user login and returns JWT token in order to check that user's logged in to application. Next this token I save in local storage by Angular6 framework.
How could I obtain that redirection with modal window in Angular6? What I'm doing wrong is that redirection dosen't work? What first step should I do in order to implement such authorization using facebook?
I would be greateful for advices.
Best Regards
I'm trying to invoke that url by get method
Which means an AJAX request … and that is of course not possible.
You need to redirect the user to the login dialog URL, not try and request it in the background - for the simple reason, that users need to be able to verify via the browser address bar, that they are indeed entering their login credentials to Facebook, and not some phishing site. If you requested it via AJAX and displayed it “within” your page, that would not be possible.
I've implemented method as misorude suggests in my Auth Service:
loginWithFacebook(appId: number, redirectUri: string) {
window.location.href = `https://www.facebook.com/v3.1/dialog/oauth?client_id=${appId}&redirect_uri=${redirectUri}&response_type=token&display=popup`;
}
Currently the page redirects to my Facebook app. Next I confirm my login by Facebook in dialog window. Then browser redirect back to my Angular app and in my url I have Social token from Facebook like on the picture below:
Next I'd like to obtain this token from url and then to implement the data flow as below:
How should I correctly get an access token and post to my backend Server as on the schema above?
I would be greateful for help
Best regards

What is it the best solution to hide a single page application private pages with Firebase?

I'm going to explain the problem better with an example, in this Firebase official example https://office-mover-demo.firebaseapp.com/ I can show the hidden page without login with a simple command in the console:
app.classList.remove('is-hidden');
Yes, of course, the data in firebase can be accessed only if a user successful logged in. So my question is: Can i do something to show the structure of the html private part only after a successful login of the user? (Only with static content and firebase auth)
From the Firebase documentation on monitoring authentication state:
// Create a callback which logs the current auth state
function authDataCallback(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
}
}
// Register the callback to be fired every time auth state changes
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(authDataCallback);
Where the snippet calls console.log, you can just as easily show/hide the HTML.
My solution to this problem - as I understand it - is to set a cookie upon user login containing the user's id or, with an additional call to Firebase, a secret visible only to the logged in client. My server can then read the cookie and determine whether the user is authorized to view the content and only then download it. Thus, I am using Firebase for authentication, but my own server for authorization.
It works, and I can also log the user in to my server using this approach just as if I had received an Oauth token.
However, lacking experience with cookies, I would like to know how secure this is!

ASP.NET MVC & Angular: Custom Attribute / ActionFilter when Session Cookies expire, want it to redirect to Login page but it doesn't always work

Details
I'm using ASP.NET MVC with Angular. If I do a hard refresh (F5), it hits the attribute I created just fine.. also when the session cookies exist it accesses it fine. but say the user is on a certain page, and the session cookie expires while he's on it.. the code will still access my Angular code, but once it's supposed to hit my Controller or probably my Attribute first.. it doesn't. So nothing works on the webpage at that point and nor does it redirect to the Login screen.
I googled around and searched this website as well but haven't found anything that works.. Any help?
My Code
Attribute for all my Controllers EXCEPT by AccountController (it causes a Redirect loop for some reason??). I put this at the top of all my controllers.
[CustomFilters.VerifySession]
My Custom Attribute
public class CustomFilters
{
public class VerifySessionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var userId = filterContext.HttpContext.Session["UserId"];
var userName = filterContext.HttpContext.Session["UserName"];
if (userId == null || userName == null)
filterContext.Result = new RedirectResult(string.Format("/Account/Login"));
}
}
}
My Login Function
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
...
Session["UserId"] = UserId;
Session["UserName"] = sql.UserProfiles.Where(c => c.UserId == UserId).Select(x => x.UserName).FirstOrDefault();
...
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="1" /> //set to 1 just for testing purposes
</authentication>
<sessionState timeout="1" /> //set to 1 just for testing purposes
</system.web>
Not quite enough detail to figure out what's happening, so a couple thoughts:
First, the forms authentication module will redirect before an unauthenticated request hits your filters or controllers. Way it works is the forms module will intercept any 401 Unauthenticated responses generated anywhere in the application and replace them with 302 redirects to the login page.
Second, these redirects won't work on an ajax request. You didn't mention if you checked the responses in your browsers' dev tools, but if you send an ajax request with an expired cookie, the browser will automatically follow the redirect issued by the forms module but won't actually redirect the user to the login page--instead you'll simply get the HTML of the login page as response data in the ajax request.
So it sounds to me like the problem you are having is that the forms module is redirecting unauthenticated requests to the login page, but this just doesn't work for ajax requests made by the angular framework.
Basically what you need is some javascript code to recognize when it's getting an unauthenticated response and actually redirect the page to the login page instead of parsing the response. My own solution (not using angular) was to simply disable the 302 redirect on unauthenticated requests, then instead have javascript handle 401 responses: Best way to handle unauthenticated request in asp.net Web Api

Facebook app and session handling

What is the way to do the app logout when the user is logged out from Facebook?
Let's consider the following situation: I've got the app that build into the webshops, so I somehow need to know the login status of the user. When the user logs into facebook and then into my app, he can 'save' or 'bookmark' the page. There's an option - to provide the logout button which logs out from the app, and then from facebook.
But my problem is the opposite: how to detect if the user has logged out from facebook - inside my app, which is built into the webshop? There's no way to detect it from the backend, only the js. Can I somehow build in the facebook login status change into my js code so it will do the check right away when my js snippet has loaded on a website?
You can make a simple graph api request like
https://graph.facebook.com/me/?access_token={your%20access%20token}
If user is logged in then you will receive a response with user information otherwise you will get a response as follows
{
"error": {
"message": "Error validating access token: This may be because the user logged out or may be due to a system error.",
"type": "OAuthException",
"code": 190,
"error_subcode": 467
}
}
Using this you can differentiate whether is user is logged in into fb or not.
Thanks,
Pranav
Could not find any reasonable solution, so did the following:
every request is directed to the app
on the app landing page Facebook JS SDK checks the login status and handles everything

Categories

Resources