应用程序服务

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />

      <membership defaultProvider="SampleMembershipProvider">
        <providers>
          <add name="SampleMembershipProvider" type="AppService.SampleMembershipProvider"/>
        </providers>
        
      </membership>
      <roleManager enabled="true" defaultProvider="SampleRoleProvider">
        <providers>
          <add name="SampleRoleProvider" type="AppService.SampleRoleProvider"/>
        </providers>
        
      </roleManager>
    </system.web>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

  <system.web.extensions>
    <scripting>
      <webServices>
        <authenticationService enabled="true"/>
        <roleService enabled="true"/>
      </webServices>
    </scripting>
  </system.web.extensions>

</configuration>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace AppService
{
    public class SampleMembershipProvider:MembershipProvider
    {
        private Dictionary<string, string> users = new Dictionary<string, string>();
        internal static string ManagerUserName = "Manager".ToLowerInvariant();
        internal static string EmployeeUserName = "Employee".ToLowerInvariant();

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            users.Add(ManagerUserName, "secret@Pa$$w0rd");
            users.Add(EmployeeUserName, "s0me@Secret");
            base.Initialize(name, config);
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            if (users.ContainsKey(username.ToLowerInvariant()))
            {
                return password.Equals(users[username.ToLowerInvariant()]);
            }
            return false;
        }

       
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace AppService
{
    public class SampleRoleProvider:RoleProvider
    {
        internal static string ManagerRoleName = "Manager".ToLowerInvariant();
        internal static string EmployeeRoleName = "Employee".ToLowerInvariant();

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetRolesForUser(string username)
        {
            if (string.Compare(username, SampleMembershipProvider.ManagerUserName, true) == 0)
            {
                return new string[] { ManagerRoleName };
            }
            else if (string.Compare(username, SampleMembershipProvider.EmployeeUserName, true) == 0)
            {
                return new string[] { EmployeeRoleName };
            }
            else
            {
                return new string[0];
            }
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            string[] roles = GetRolesForUser(username);
            foreach (var role in roles)
            {
                if (string.Compare(role, roleName, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }

}

客户端

<Window x:Class="AuthenticationExam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Label VerticalAlignment="Center" Margin="5" Grid.Row="0" Grid.Column="0" Content="Username:" />
        <Label VerticalAlignment="Center" Margin="5" Grid.Row="1" Grid.Column="0" Content="Password:" />
        <TextBox x:Name="textUsername" Margin="5" Grid.Row="0" Grid.Column="1" />
        <PasswordBox x:Name="textPassword" Margin="5" Grid.Row="1" Grid.Column="1" />
        <Button x:Name="buttonLogin" Click="OnLogin" Grid.Row="2" Grid.Column="1" Margin="5" Content="Login" />
        <TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" x:Name="labelValidatedInfo" Visibility="Hidden" Text="User Validated" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>

</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AuthenticationExam
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLogin(object sender, RoutedEventArgs e)
        {
             try
            {
                labelValidatedInfo.Visibility = Visibility.Hidden;
                if (Membership.ValidateUser(textUsername.Text,
                      textPassword.Password))
                {
                    // user validated!
                    labelValidatedInfo.Visibility = Visibility.Visible;
                }
                else
                {
                    MessageBox.Show("Username or password not valid",
                          "Client Authentication Services", MessageBoxButton.OK,
                          MessageBoxImage.Warning);
                }
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "Client Application Services",
                      MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
    }

}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="http://localhost:55555/AppServices/Authentication_JSON_AppService.axd" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="http://localhost:55555/AppServices/Role_JSON_AppService.axd" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

C#基于用户和角色的验证,服务端web 客户端wpf的更多相关文章

  1. 基于Select模型的Windows TCP服务端和客户端程序示例

    最近跟着刘远东老师的<C++百万并发网络通信引擎架构与实现(服务端.客户端.跨平台)>,Bilibili视频地址为C++百万并发网络通信引擎架构与实现(服务端.客户端.跨平台),重新复习下 ...

  2. Qt实现基于多线程的文件传输(服务端,客户端)

    1. 效果 先看看效果图 这是传输文件完成的界面 客户端 服务端 2. 知识准备 其实文件传输和聊天室十分相似,只不过一个传输的是文字,一个传输的是文件,而这方面的知识,我已经在前面的博客写过了,不了 ...

  3. 使用 Shiro 设计基于用户、角色、权限的通用权限管理系统

    一.前言 在大型的信息管理系统中,经常涉及到权限管理系统 下面来个 demo,很多复杂的系统的设计都来自它 代码已经放到github上了,地址:https://github.com/larger5/s ...

  4. .net平台 基于 XMPP协议的即时消息服务端简单实现

    .net平台 基于 XMPP协议的即时消息服务端简单实现 昨天抽空学习了一下XMPP,在网上找了好久,中文的资料太少了所以做这个简单的例子,今天才完成.公司也正在准备开发基于XMPP协议的即时通讯工具 ...

  5. 项目源码--JAVA基于LBS地理位置信息应用的服务端

    技术要点: 1. LBS应用框架服务端实现 2. JAVA服务端技术 3. MYSQL数据库技术 4. 源码带详细的中文注释 ......   详细介绍: 1. LBS应用框架服务端实现 此套源码是基 ...

  6. 基于SignalR的服务端和客户端通讯处理

    SignalR是一个.NET Core/.NET Framework的实时通讯的框架,一般应用在ASP.NET上,当然也可以应用在Winform上实现服务端和客户端的消息通讯,本篇随笔主要基于Sign ...

  7. 基于TCP协议套接字,服务端实现接收客户端的连接并发

    基于TCP协议套接字,服务端实现接收客户端的连接并发 服务端 import socket from multiprocessing import Process server=socket.socke ...

  8. 写一个基于TCP协议套接字,服务端实现接收客户端的连接并发

    ''' 写一个基于TCP协议套接字,服务端实现接收客户端的连接并发 ''' client import socket import time client = socket.socket() clie ...

  9. openssl实现双向认证教程(服务端代码+客户端代码+证书生成)

    一.背景说明 1.1 面临问题 最近一份产品检测报告建议使用基于pki的认证方式,由于产品已实现https,商量之下认为其意思是使用双向认证以处理中间人形式攻击. <信息安全工程>中接触过 ...

随机推荐

  1. 第一次使用docker for windows 遇到的坑

    原文:第一次使用docker for windows 遇到的坑 1. 目前win10安装docker, 不需要安装其他工具,可直接到官网下载 2. 此版本的docker可同时运行Windows con ...

  2. php定时任务(自己)

    php定时任务(自己) 一.总结 一句话总结:可用php.exe连接php文件和bat文件,bat文件在计划任务中可以设置定时执行, 二. 1.php 2.bat E: "D:\softwa ...

  3. PHP移动互联网开发笔记(5)——基础函数库

    一.数学函数库 ● floor 舍一取整(向下取整) float floor (float $value); <?php echo(floor(0.60)."<br>&qu ...

  4. 【codeforces 604D】Moodular Arithmetic

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  5. C#基础readonly 与const

    readonly 与 const readonly是运行时常量,const是编译期常量(在编译过程中已经把使用该值的都用值替代,不分配内存)readonly灵活性高,const效率高 readonly ...

  6. svn服务配置

    1关闭所有svn服务 nie-xiao-bo-mac-pro:svnproject mac$ killall -9 svnserve 2.开启某文件路径svn服务 nie-xiao-bo-mac-pr ...

  7. MVVM初步搭建应用

    MVVM模式:利用 prism Microsoft.Practices.Prism.dllWPF Interaction框架简介 添加Interactions库的引用.主要添加如下两个DLL: Mic ...

  8. svn创建版本库和删除版本库

    作者:朱金灿 来源:http://blog.csdn.net/clever101 svn创建版本库的做法:使用cd命令进入版本仓库的根目录,我的是E:\Repository,然后运行命令: svnad ...

  9. 【t076】竞赛排名

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 某市组织了一次中学生科技全能竞赛,每个选手要参加数学.物理.化学.天文.地理.生物.计算机和英语共八项 ...

  10. 【BZOJ 1037】[ZJOI2008]生日聚会Party

    [题目链接]:http://www.lydsy.com/JudgeOnline/problem.php?id=1037 [题意] [题解] /* 设f[i][j][k][l] 表示前i个人中,有j个男 ...