简体   繁体   中英

How to prevent from editing one part of localStorage

I got an example code from [JasonWatMore][1] which is role based authorization I tried to do it myself and it works fine but I found one big problem.

I want to prohibit interference with the user roles

Now in authentication.service.t s I got

   login(username: string, password: string) {
        return this.http.post<any>(`/users/authenticate`, { username, password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }

                return user;
            }));
    }

Where all data from backend is located in localSotrage which looks like

{id: 1, username: "admin", firstName: "Admin", lastName: "User", role: "User",…}
firstName: "Admin"
id: 1
lastName: "User"
role: "User"
token: "fake-jwt-token.Admin"
username: "admin"

and now when I opening developer tools I can edit role from User to Admin and I got all access to admin pages.

Is there any way to secure this role parametr?

And there is guard

export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

How should I secure localStorage? I also want to secure elements on page for example if Admin then show else not ( I know how to do it but there is a problem because everyone can edit localStorage) So I don't want to only secure routes

User service variables for storing that kind of data. But still if you only want to use localstorage, encrypt the data using bcrypt or something before storing. and decrypt it after getting it from localstorage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM