Best way to get user roles
bekirtaskin opened this issue · 2 comments
bekirtaskin commented
Hello,
I am trying to get user roles. Roles are defined in JWT, but cannot find any role related attribute in Credential.
Thanks in advance
ahmetozrahat commented
I think this is something not relevant to this package thus needed to be done on your side. You can use jwt_decoder or you could parse it yourself.
The access token retrieved from authentication could be used to retrieve the needed information.
Map<String, dynamic> userProfile = JwtDecoder.decode(token.accessToken);
Then you could convert this map to a dart class and retrieve the roles.
import 'package:json_annotation/json_annotation.dart';
part 'user_profile.g.dart';
@JsonSerializable()
class UserProfile {
@JsonKey(name: 'Name')
final String? name;
@JsonKey(name: 'Surname')
final String? surname;
@JsonKey(name: 'Email')
final String? email;
@JsonKey(name: 'role')
final List<String>? roles;
UserProfile({
this.name,
this.surname,
this.email,
this.roles,
});
factory UserProfile.fromJson(Map<String, dynamic> json) =>
_$UserProfileFromJson(json);
Map<String, dynamic> toJson() => _$UserProfileToJson(this);
}
UserProfile profile = UserProfile.fromJson(userProfile);
bool isRoleExists = profile.roles?.contains("your:permission");
bekirtaskin commented
Thank you. I was hoping for some mapping in the plugin but this will do.