Hi thanks! I tried to create custom Athorizate Attribute which is deriveder from AbpMvcAuthorizeAttribute and I have problem with
HandleUnauthorizedRequest
. This method is never called in this CustomAttribute. The same problem is in
AbpAuthorizeAttribute
also not called.
My implementation:
public class CustomMvcAuthorizeAttribute : AbpMvcAuthorizeAttribute
{
public ILogger Logger { get; set; }
public string[] Permissions { get; set; }
public bool RequireAllPermissions { get; set; }
public VSDMvcAuthorizeAttribute(params string[] permissions) :base(permissions)
{
Logger = NullLogger.Instance;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var httpContext = filterContext.HttpContext;
**var message = string.Format("'{0}' unauthorize access.", httpContext.Request.CurrentExecutionFilePath );
Logger.Security(message); // my custom security log**
if (!httpContext.Request.IsAjaxRequest())
{
base.HandleUnauthorizedRequest(filterContext);
return;
}
httpContext.Response.StatusCode = httpContext.User.Identity.IsAuthenticated == false
? (int)System.Net.HttpStatusCode.Unauthorized
: (int)System.Net.HttpStatusCode.Forbidden;
httpContext.Response.SuppressFormsAuthenticationRedirect = true;
httpContext.Response.End();
}
Thanks for help
Solved by virtual keyword in action :) :D
Hi what if I want to make query based on extended attribute ?
When I do this:
private readonly IRepository<MYOrganizationUnit, long> _organizationUnitRepository;
I need this:
_organizationUnitRepository.FirstOrDefault( x => x.custmAttribute = "xxx");
I got error, dependency is not satisfied
Thanks
Thanks. Works!
I have another question. In CORE project i create MYOrganizationUnitManager class. I need to insert orgnization unit there:
public class MYOrganizationUnitManager : IDomainService
{
private readonly UserManager _userManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly OrganizationUnitManager _organizationUnitManager;
public MYOrganizationUnitManager(
UserManager userManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
OrganizationUnitManager organizationUnitManager
)
{
this._userManager = userManager;
_organizationUnitRepository = organizationUnitRepository;
_organizationUnitManager = organizationUnitManager;
}
public virtual async Task CreateOuStructure()
{
// Remove all OU first
// Get ROOT OU
var rootUnit = _organizationUnitRepository.GetAll().FirstOrDefault(x => x.DisplayName == "ROOT");
if (rootUnit == null)
{
// Create fresh root unit
rootUnit = await CreateOu("ROOT", "EN000000");
}
var regionUnit = await CreateOu("Child UNIT", "EN570000", rootUnit.Id);
}
protected virtual async Task<MYOrganizationUnit> CreateOu(string displayName, string hermesUnitCode, long? parentId = null)
{
var ou = new MYOrganizationUnit() { DisplayName = displayName, CustomUnitCode = customUnitCode ,ParentId = parentId };
await _organizationUnitManager.CreateAsync(ou);
await _organizationUnitManager.UnitOfWorkManager.Current.SaveChangesAsync();
return ou;
}
}
I´m using this (MYOrganizationUnitManager ) in MYApplicationService, and I got this error:
Abp.AbpException: There is no such an entity with given primary key. Entity type: Abp.Organizations.OrganizationUnit, primary key: 13
v Abp.Domain.Repositories.AbpRepositoryBase`2.<GetAsync>d__16.MoveNext() v D:\Halil\GitHub\aspnetboilerplate\src\Abp\Domain\Repositories\AbpRepositoryBase.cs:řádek 81
--- Konec trasování zásobníku z předchozího místa, ze kterého byla vyvolána výjimka ---
v System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
v System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
v System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
v Abp.Threading.InternalAsyncHelper.<AwaitTaskWithPostActionAndFinallyAndGetResult>d__5`1.MoveNext() v D:\Halil\GitHub\aspnetboilerplate\src\Abp\Threading\InternalAsyncHelper.cs:řádek 120
--- Konec trasování zásobníku z předchozího místa, ze kterého byla vyvolána výjimka ---
v System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
v System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
v System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
v Abp.Organizations.OrganizationUnitManager.<GetCodeAsync>d__10.MoveNext() v D:\Halil\GitHub\module-zero\src\Abp.Zero\Organizations\OrganizationUnitManager.cs:řádek 67
--- Konec trasování zásobníku z předchozího místa, ze kterého byla vyvolána výjimka ---
v System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
v System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
This code do not insert new entity to DB, but ID is generated, when iserting new entity i get above error
await _organizationUnitManager.UnitOfWorkManager.Current.SaveChangesAsync();
¨
Thanks for help
Please can you post code which solved your issue? Thanks !
Hello I finaly used Mixed Auth project for owin windows SSO. (<a class="postlink" href="https://github.com/MohammadYounes/OWIN-MixedAuth">https://github.com/MohammadYounes/OWIN-MixedAuth</a>)
I had to create MySession class which extended base AbpSession class, because I have problem with UserId property which is not setted.
public class MySession : ClaimsAbpSession
{
public MySession(IMultiTenancyConfig multiTenancy) : base(multiTenancy)
{
}
protected object ExecuteScalar(SqlCommand command)
{
object obj2;
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
{
connection.Open();
command.Connection = connection;
using (command)
{
obj2 = command.ExecuteScalar();
}
connection.Close();
}
return obj2;
}
public override long? UserId
{
get
{
var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
if (claimsPrincipal == null)
{
return null;
}
var claimsIdentity = claimsPrincipal.Identity as WindowsIdentity;
if (claimsIdentity == null)
{
return base.UserId;
}
if (claimsIdentity.Name == "")
{
return null;
}
SqlCommand command = new SqlCommand("SELECT Id from AbpUsers where UserName = @UserName AND IsDeleted = 0; SELECT SCOPE_IDENTITY();");
SqlParameter parmaeter = new SqlParameter { DbType = DbType.String, ParameterName = "@UserName", Value = claimsIdentity.Name };
command.Parameters.Add(parmaeter);
var vyseldek = Convert.ToInt32(ExecuteScalar(command));
return vyseldek;
}
}
}
I got user id from DB by his windows Indentity name.
In web module preIntialize method: IocManager.Register<IAbpSession, MySession>();
Anonymus auth must be enabled in Web project , ofcourse windows auth too.
This is my solution, if you have better way share it.
When I=m creating user by your method i got this error (only on IE, chrome works with out error (this I do not understand)):
V aplikaci / došlo k chybě serveru.
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Popis: Při provádění aktuálního webového požadavku došlo k neošetřené výjimce. Další informace o chybě a o jejím původu v kódu naleznete v trasování zásobníku.
Podrobnosti o výjimce: System.Data.Entity.Core.UpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Zdrojová chyba:
Řádek 475: Logger.Debug("Vytváření uživatele: " + createUser.UserName);
Řádek 476:
Řádek 477: var newUser = _userManager.Create(createUser);
Řádek 478:
Řádek 479: Logger.Debug("Konec vytváření uživatele: ");
Zdrojový soubor: C:\Projects\\TT.Web\Controllers\AccountController.cs Řádek: 477
I must create manual insert by this code to get it work. Create user with user manager have error above...
SqlCommand command = new SqlCommand(
"INSERT INTO [AbpUsers] ([TenantId] ,[AuthenticationSource],[Name],[Surname],[UserName],[Password] ,[EmailAddress]"+
",[IsEmailConfirmed],[EmailConfirmationCode],[PasswordResetCode] ,[LastLoginTime],[IsActive],[IsDeleted],[DeleterUserId]" +
",[DeletionTime] ,[LastModificationTime],[LastModifierUserId],[CreationTime],[CreatorUserId] ,[Company] )" +
"VALUES ( @TenantId, @AuthenticationSource, @Name, @Surname, @UserName, @Password, @EmailAddress, @IsEmailConfirmed, @EmailConfirmationCode , @PasswordResetCode, " +
"@LastLoginTime, @IsActive, @IsDeleted, @DeleterUserId, @DeletionTime, @LastModificationTime , @LastModifierUserId, @CreationTime," +
"@CreatorUserId, @Company ); SELECT SCOPE_IDENTITY();");
SqlParameter parameter3 = new SqlParameter { DbType = DbType.Int32, ParameterName = "@TenantId", Value = 1 };
SqlParameter parameter4 = new SqlParameter { DbType = DbType.String, ParameterName = "@AuthenticationSource", Value = DBNull.Value };
SqlParameter parameter5 = new SqlParameter { DbType = DbType.String, ParameterName = "@Name", Value = createUser2.UserName };
SqlParameter parameter6 = new SqlParameter { DbType = DbType.String, ParameterName = "@Surname", Value = createUser2.UserName };
SqlParameter parameter7 = new SqlParameter { DbType = DbType.String, ParameterName = "@UserName", Value = createUser2.UserName };
SqlParameter parameter8 = new SqlParameter { DbType = DbType.String, ParameterName = "@Password", Value = createUser2.UserName };
SqlParameter parameter9 = new SqlParameter { DbType = DbType.String, ParameterName = "@EmailAddress", Value = createUser2.UserName };
SqlParameter parameter10 = new SqlParameter { DbType = DbType.Boolean, ParameterName = "@IsEmailConfirmed", Value = true };
SqlParameter parameter11 = new SqlParameter { DbType = DbType.String, ParameterName = "@EmailConfirmationCode", Value = DBNull.Value };
SqlParameter parameter12 = new SqlParameter { DbType = DbType.String, ParameterName = "@PasswordResetCode", Value = DBNull.Value };
SqlParameter parameter13 = new SqlParameter { DbType = DbType.DateTime, ParameterName = "@LastLoginTime", Value = DBNull.Value };
SqlParameter parameter14 = new SqlParameter { DbType = DbType.Boolean, ParameterName = "@IsActive", Value = true };
SqlParameter parameter15 = new SqlParameter { DbType = DbType.Boolean, ParameterName = "@IsDeleted", Value = false };
SqlParameter parameter16 = new SqlParameter { DbType = DbType.Int32, ParameterName = "@DeleterUserId", Value = DBNull.Value };
SqlParameter parameter17 = new SqlParameter { DbType = DbType.DateTime, ParameterName = "@DeletionTime", Value = DBNull.Value };
SqlParameter parameter18 = new SqlParameter { DbType = DbType.DateTime, ParameterName = "@LastModificationTime", Value = DBNull.Value };
SqlParameter parameter19 = new SqlParameter { DbType = DbType.Int32, ParameterName = "@LastModifierUserId", Value = DBNull.Value };
SqlParameter parameter20 = new SqlParameter { DbType = DbType.DateTime, ParameterName = "@CreationTime", Value = DateTime.Now };
SqlParameter parameter21 = new SqlParameter { DbType = DbType.Int32, ParameterName = "@CreatorUserId", Value = 2 };
SqlParameter parameter22 = new SqlParameter { DbType = DbType.String, ParameterName = "@Company", Value = createUser2.Com };
command.Parameters.Add(parameter3);
command.Parameters.Add(parameter4);
command.Parameters.Add(parameter5);
command.Parameters.Add(parameter6);
command.Parameters.Add(parameter7);
command.Parameters.Add(parameter8);
command.Parameters.Add(parameter9);
command.Parameters.Add(parameter10);
command.Parameters.Add(parameter11);
command.Parameters.Add(parameter12);
command.Parameters.Add(parameter13);
command.Parameters.Add(parameter14);
command.Parameters.Add(parameter15);
command.Parameters.Add(parameter16);
command.Parameters.Add(parameter17);
command.Parameters.Add(parameter18);
command.Parameters.Add(parameter19);
command.Parameters.Add(parameter20);
command.Parameters.Add(parameter21);
command.Parameters.Add(parameter22);
It sems that problem is with owin.
When I enebale windows auth and disable allow anonymus - I need the windows login form. I need to login user based on his windows account automaticly and use your ABP roles managment, ABPAuthorize .... I have no idea how to solve this
Hello, I did it like you wrote. Burt htere is little problem, I must enable Windows Auth in project, but when I enable it in web config by:
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
I got this error:
Request filtering module is configured to deny the request, the query string is too long.
Detailed Error Information: Module RequestFilteringModule Notification BeginRequest Handler ExtensionlessUrlHandler-Integrated-4.0 Error Code 0x00000000
Requested URL http://localhost:6334/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252FAccount%2525252FLogin%2525253FReturnUrl%2525253D%252525252FAccount%252525252FLogin%252525253FReturnUrl%252525253D%25252525252FAc.......
Thanks for help
Hello, thanks.
I crated new issue there, and I found bug probably and his probable cause. See there: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues/714">https://github.com/aspnetboilerplate/as ... issues/714</a>
Sample project was updated, link is on git issue.
BTW: Where would you paste code to auto SignIn when User starts the application ? I can get UserName from current thread and sign on using your method with db. But I´m not sure where paste this logic.
Thanks!