ASP Net Identity 2.0承载令牌和角色错误

时间:2018-09-10 15:05:01

标签: authentication asp.net-web-api authorization roles asp.net-identity-2

当用户没有角色但有不记名令牌时,我如何进行自定义错误响应?

默认情况下,当用户没有令牌和角色时,Identity 2.0会发送相同的响应。

请告诉我解决该问题必须重写的方法。

我使用Asp net Web Api 2.0。

请求标头:

session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = '';
$DB_PASS = '';
$DB_NAME = '';

// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}


// before doing anything with the posted field value
// check to see if the form was actually posted
// or is this the first time the page has been laoded


if($_SERVER['REQUEST_METHOD'] == 'POST'){

    // Now we check if the data was submitted, isset will check if the data exists.
    if ( !isset($_POST['username'], $_POST['password'], $_POST['email'])) {
        // Could not get the data that should have been sent.
        die ('Please complete the registration form!');
    }

    // Also check if the submitted values are empty
    if ( empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
        // One or more values are empty...
        die ('Please complete the registration form!');
    }
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        die ('Email is not valid!');
    }
    if (preg_match('^[0-9A-Za-z_]+$^', username) == 0) {
        die ('Invalid username!');
    }
    if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
        die ('Password must be between 5 and 20 characters long.');
    }
    // We need to check if the account with that username exists
    if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
        // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
        $stmt->bind_param('s', $_POST['username']);
        $stmt->execute(); 
        $stmt->store_result(); 
        // Store the result so we can check if the account exists in the database.
        if ($stmt->num_rows > 0) {
            // Username already exists
            echo 'Username exists, please choose another!';
        } else {
            // Username doesnt exists, insert new account
            if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
                $stmt->bind_param('sss', $_POST['username'], password_hash($_POST['password'], PASSWORD_DEFAULT), $_POST['email']);
                $stmt->execute();
                echo 'You have successfully registered, you can now login!';
            } else {
                echo 'Could not prepare statement!';
            }
        }
        $stmt->close();
    } else {
        echo 'Could not prepare statement!';
    }

// HTML CODE TO FOLLOW after the `?>`
?>

响应头:

content-type: application/json
accept: application/json
authorization: bearer {token_value}

当用户没有角色或令牌时,响应是相同的。 响应码为401

cache-control: no-cache
pragma: no-cache
content-type: application/json; charset=utf-8
expires:-1
server: Microsoft-IIS/10.0
x-aspnet-version: 4.0.30319
www-authenticate: Bearer
x-sourcefiles:
=?UTF-8?B?RDpcUHJvamVjdCBWUzE3XEJveGluZ0FwcFxBcHBCb3hpbmdcQXBwQm94aW5nXGFwaVxWYWx1ZXNcVXNlcg==?=
x-powered-by: ASP.NET
date: Tue, 11 Sep 2018 20:08:14 GMT
content-length: 61
{"Message":"Authorization has been denied for this request."}

控制器:

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            var roleManager = context.OwinContext.GetUserManager<ApplicationRoleManager>();



            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);


            String roles = String.Empty;

            foreach (var roleClaim in user.Roles)
            {
                ApplicationRole rol = null;
                rol = roleManager.FindById(roleClaim.RoleId);
                if (rol != null)
                    roles += rol.Name + ", ";
            }

            AuthenticationProperties properties = CreateProperties(user.UserName, roles.ToString());  


            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);

        }

响应令牌:

[HttpPost]
    [Authorize(Roles ="Admin")]
    [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
    [Route("Admin")]
    public String ForAdmin()
    {
        return "Only Admin";
    }

0 个答案:

没有答案