Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Custom Authentication Implementation in C#

Tech Sep 12 2

Custom Authorization Attribute

The following implementation extends AuthorizeAttribute to manage custom authentication logic:

public class CustomAuthAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (SkipAuthorization(actionContext) || IsAuthenticated(actionContext))
            return;

        actionContext.Response = CreateUnauthorizedResponse();
    }

    private HttpResponseMessage CreateUnauthorizedResponse()
    {
        var response = ServiceResponse<bool>.WarningResponse(401, CommonConst.Msg_NoLogin, false);
        return JsonHelper.ToHttpResponseMessage(response);
    }

    private static bool SkipAuthorization(HttpActionContext actionContext)
    {
        var actionAttributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>();
        if (!actionAttributes.Any())
        {
            var controllerAttributes = actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>();
            return controllerAttributes.Any();
        }
        return true;
    }

    private bool IsAuthenticated(HttpActionContext actionContext)
    {
        var authHeader = Guid.Empty.ToString();
        if (actionContext.Request.Headers.Authorization != null)
        {
            authHeader = actionContext.Request.Headers.Authorization.ToString();
        }

        var user = OperatorProvider.Provider.GetCurrent(authHeader);
        return user != null;
    }
}

Header Value Retrieval

The following method retrieves header values for authentication validation:

private bool IsAuthenticated(HttpActionContext actionContext)
{
    var tokenValue = Guid.Empty.ToString();
    var openIdValue = string.Empty;

    actionContext.Request.Headers.TryGetValues("Token", out var tokens);
    actionContext.Request.Headers.TryGetValues("OpenId", out var openIds);
    
    if (tokens.IsNotNull() && tokens.Any() && openIds.IsNotNull() && openIds.Any())
    {
        tokenValue = tokens.FirstOrDefault();
        openIdValue = openIds.FirstOrDefault();

        var cacheEntry = CacheHelper.GetCache(tokenValue);
        if (cacheEntry.IsNotNull())
            return true;

        var userUrl = HttpUtility.UrlDecode(ConfigurationManager.AppSettings["sso_req_user_url"]);
        var requestUrl = string.Format(userUrl, openIdValue, tokenValue);
        var request = WebRequest.Create(requestUrl) as HttpWebRequest;
        request.Method = "GET";
        request.ContentType = "application/json";
        
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var responseData = reader.ReadToEnd();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var userData = JsonConvert.DeserializeObject<SSOUser>(responseData);
                    var userId = Guid.Parse(userData.OpenId);
                    CacheHelper.SetCache(tokenValue, userId);
                    return true;
                }
            }
        }
    }
    return false;
}

Base API Controller

The base controller prvoides access to current user information through a property:

[CustomAuth]
public class BaseController : ApiController
{
    public OperatorModel CurrentUser
    {
        get
        {
            var authHeader = HttpContext.Current.Request.Headers.GetValues("authorization");
            var token = Guid.Empty.ToString();
            if (authHeader != null && authHeader.Length > 0)
                token = authHeader[0];
            
            var currentUser = OperatorProvider.Provider.GetCurrent(token);
            if (currentUser == null)
            {
                currentUser = new OperatorModel { LoginName = "admin" };
            }
            return currentUser;
        }
    }
}

Front end Integration with Vue.js

Token Utility Class

import Cookies from 'js-cookie'

const TokenKey = 'hs_t'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

Login Comopnent

<template>
  <div class="login-container">
    <el-form ref="model" :model="model" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">教师中心</h3>
      </div>

      <el-form-item prop="LoginName">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="LoginName" v-model="model.LoginName" placeholder="登录名" name="LoginName" type="text" tabindex="1"
          autocomplete="on" />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input :key="passwordType" ref="password" v-model="model.password" :type="passwordType" placeholder="密码"
            name="password" tabindex="2" autocomplete="on" @keyup.enter.native="login" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="login">
        登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { deepClone } from "@/utils";
import { setToken } from '@/utils/auth'
import { login } from "@/api/user";

const defaultModel = {
  LoginName: "",
  password: "",
  orgCode: "",
  phone: "",
  UserType: "Teacher"
};

export default {
  name: 'Login',
  data() {
    return {
      model: deepClone(defaultModel),
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        LoginName: [
          { required: true, message: "请输入登录名", trigger: 'blur' }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: 'blur' }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    async login() {
      let isValid = true;
      this.$refs.model.validate(valid => {
        isValid = valid;
      });
      
      if (!isValid) return false;
      
      const response = await login(this.model);
      console.log(response);
      
      if (response.code === 200) {
        setToken(response.data);
        this.$router.push("/");
      }
    }
  }
}
</script>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.